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

Freeing resources (threads) in web app

Maciej Kolodziej

Joined: Feb 11, 2002
Posts: 26
I have a web application which runs several threads. These threads are initialized in a class which is instantiated by a servlet and then put into servlet session when a user logs on the system.
When the user logs out I want to stop these threads. I can do this by getting the class instance from the session and calling a method which stops the threads.
But what can I do when the user closes his browser without logging out? How can I stop running threads when the session is closed (timeout)? Is there any method (like in EJB) which allows to norify a bean that it should free its resources?
The only idea I've got is to define a finalize method in that class. But that would stop these threads later when the instance is garbage collected and not when the session is invalidates.
Does anyone know any better solution of this problem?

Dominic Paquette
Ranch Hand

Joined: Dec 13, 2002
Posts: 64
Maybe if you create a class that implements the SessionListener interface. This interface defines 2 methods:
public void sessionCreated(HttpSessionEvent e)
public void sessionDestroyed(HttpSessionEvent e)
sessionDestroyed will be called whenever a session times out or HttpSession.invalidate() is called. However I'm not sure if the HttpSession object is still valid when the function is called.
I have to go to lunch now but I'll look into it when I come back
Hope this helps
Maciej Kolodziej

Joined: Feb 11, 2002
Posts: 26
Thanks Dominic - your post helped me to find an answer. I haven't tested it yet, but I guess the best way is to implement javax.servlet.http.HttpSessionBindingListener. The javax.servlet.http.HttpSession javadoc says:
"When an application stores an object in or removes an object from a session, the session checks whether the object implements HttpSessionBindingListener. If it does, the servlet notifies the object that it has been bound to or unbound from the session."
Kyle Brown
Ranch Hand

Joined: Aug 10, 2001
Posts: 3892
Just out of curiosity -- why are you starting all these threads? What are they doing? This seems like an inefficient way to do things...

Kyle Brown, Author of Persistence in the Enterprise and Enterprise Java Programming with IBM Websphere, 2nd Edition
See my homepage at for other WebSphere information.
I agree. Here's the link:
subject: Freeing resources (threads) in web app
It's not a secret anymore!