Thursday, May 19, 2011

Free resources associated with web clients

Imagine we have the following problem. Resources are kept open for web clients as long as the clients are using them. When they leave, the resources have to be closed.

Technically, we can say as long as the HttpSession is alive in the web container, the resources are kept open. When the HttpSession is invalidated, we need to call a method that frees the resources.

A solution is to use the HttpSessionBindingListener to solve this problem.

The idea is to create a class that implements this interface. The unbound method contains or refers to the clean-up code. Whenever resources are opened, an instance of this class is created and saved to the corresponding session. When the session invalidates, which can happen by timeout, the web container automatically calls the method of the object in order to free open resources.

The class:

package com.javaeenotes;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

public class Janitor implements HttpSessionBindingListener {

public void valueBound(HttpSessionBindingEvent arg0) {

public void valueUnbound(HttpSessionBindingEvent arg0) {
// Start some cleaning here.

Use the HttpSession.setAttribute() method to save an instance of this class to the session.

No comments:

Post a Comment