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

destroy method and synchronization

Brij Garg
Ranch Hand

Joined: Apr 29, 2008
Posts: 234
We know container invokes the init method once and then each client request is handled by a new thread.

Now suppose number of different threads are running then

Is it possible that container calls the destroy method when few threads are still running ?

Do we need to synchronized the destroy method if we override this method?
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

No, the destroy method and access to the destroy method is managed by the container. Besides, synchronising the method will have no effect (assuming it is called once) unless other methods in the class are also synchronised. If you are really worried you should look at read and write locks rather than mutual exclusion (mutex) locks, but I've never been bothered by the destroy method at all.
Amol Nayak
Ranch Hand

Joined: Oct 26, 2006
Posts: 218
This is the description in the Javadocs for javax.servlet.Servlet
Hope this should clear your doubts..
Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. This method is only called once all threads within the servlet's service method have exited or after a timeout period has passed. After the servlet container calls this method, it will not call the service method again on this servlet.
This method gives the servlet an opportunity to clean up any resources that are being held (for example, memory, file handles, threads) and make sure that any persistent state is synchronized with the servlet's current state in memory
I agree. Here's the link:
subject: destroy method and synchronization
It's not a secret anymore!