Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Freeing resources (threads) in web app

 
Maciej Kolodziej
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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?
TIA,
MK
 
Dominic Paquette
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
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
Dominic
 
Maciej Kolodziej
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Ranch Hand
Posts: 3892
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic