servlet response time is slow for first request

2019-02-25 21:41发布

问题:

Servlet response time slow only for 1st request

Response time

1st request is 10.5 seconds.

further request 2.5 seconds.

From few java resources i got to know that the servlet loads the required classes for the first time during the first request and reuses the same for further requests and hence the delay

Fix 1: I created a dummy request within the servlet immediately after the execution of init() method.

Response time : 2.5 seconds for all requests through user agents.

Fix 2: I tried loading possible classes in the startup of servlet

Response time : for first request is 6 seconds. 2.5 seconds for other requests.

Is there are any other possibility of achieving the same because i believe that method 1 needs code change when there is a change in the url of the application (port number, resource path, etc) and response time of method 2 is not sufficient.

I have already set loadOnStartup=1 for my servlet.

回答1:

you can also use load-on-startup param in web.xml to load and intitiliaze your servlet on starttime.

<servlet>
    <servlet-name>MyServlet</servlet-name>
    <display-name>My Servlet</display-name>
    <servlet-class>com.foo.MyServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>