File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes How init method is called only once Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "How init method is called only once" Watch "How init method is called only once" New topic

How init method is called only once

Shasi Sekar

Joined: Aug 22, 2008
Posts: 23
Hi All,

I digged into servlet source code and was not able to find what check is made, so that the init and destroy methods are called only once. It would be great if any body helps me to understand better

Thanks in advance
Shasi Sekar
Piyush Mangal
Ranch Hand

Joined: Jan 22, 2007
Posts: 196
Servlets are loaded and instantiated by Servlet Container. It is Servlet container which calls init() only once when servlet is instantiated and calls destroy() when it is about to unload the servlet so you will not find any call to these methods in Servlet API. Please read servlet lifecycle for more details.
Pondurai Singh
Ranch Hand

Joined: Jun 27, 2011
Posts: 35
Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet. The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.

Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.

Life Cycle of a Servlet refernece

Software Developer, Oracle Java Certification Training Labs at EPractize Labs.
I agree. Here's the link:
subject: How init method is called only once
It's not a secret anymore!