< Prev
Next >

Lifecycle methods of Servlet

Servlet Container calls three methods during the different stages of a Servlet. These methods are part of Servlet interface, which is used to develop Servlets. The Servlet interface is part of javax.servlet package. Let's see and understand each of these methods one by one -

The Servlet Container calls the destroy() method just once in the lifetime of a Servlet instance.

When and why the destroy() method is called by the Servlet Container?
The Servlet Container may call the destroy() method on the Servlet class when an exception is thrown during the execution of service() method which says the Servlet is permanently unavailable.

What happens after the destoy() method is called?
When a Servlet Container decides to destroy an instance of Servlet, it stops taking any new user request for this particular Servlet. Meanwhile, the Servlet Container waits until all the threads currently executing the service() method finish their job and eventually the Servlet Container calls the destroy() method. Calling destroy method makes sure there are no references to the object of this Servlet and thus making it eligible for garbage collection.

Why implementing a destroy() method is useful?
We can implement destoy() method in our Servlet class to perform some finalization steps before the Servlet instance is destroyed by the Servlet Container.

Syntax of destroy() method

public void destroy()

Please share this article -

< Prev
Next >
< Servlet LifeCycle
Install Apache Tomcat Web Server >


Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page



Please check our latest addition