When Servlets are Loaded

If you are developing web applications using Java based technologies, JSP or Servlets. You must be familiar with the loading time of Servlets. First lets see whats mean by loading.

If you see the Servlet life cycle. Its as follows:

1. First of all init() method is called (this is called loading)
2. For each request, service() method is called. Which process the request and sends response to user. In case of HttpServlet, the service() method delegates the request processing to doGet(...) or doPost(...), depending on type of request.
3. When you undeploy you web app or stop Tomcat from running, destroy() method is called.

You see, init() and destroy() are called only once, after you deploy your application. After serving user request, the servlet instance remains in memory to serve other requests. But the question is, when does the init() method is called first time, or when does the servlet loaded?

If you do not do any explicit configuration, the servlet is loaded when first request comes to that servlet. So in this case, when user hits example.com/AbcServlet ... the AbcServlet's init() method is called and the servlet gets loaded into memory.

So it is the default behaviour, but we can also enforce Tomcat (or servlet container) to loaded the servlet before first request comes. For example, you may like to load AbcServlet when you deploy you web application into Tomcat. why? so that when first request comes, the time to load can be saved, and first user may get response very fast.

But what to do to enforce Tomcat to load the Servlet when you deploy you application. You just need to set load-on-startup parameter in your serlvet configuration in web.xml file: