Cleaning Up Java Sessions

By | May 6, 2008

As part of a migration from Resin 1.3 to Tomcat 5 we had to migrate servers that are session based. Because we wanted to measure the time someone was on the website a listener had to be used. In resin this was done by implementing a HttpSessionBindingListener. But when we migrated to tomcat our measurements no longer worked.

Once a session became invalidated the HttpSessionBindingListener valueUnbound method was called. During this call we used the getLastAccessedTime() on the session to figure out how long the session was idle before the session was cleaned up.

During the investigation as to why the idle time was no longer logged we found out that for some reason the valueUnbound was no longer working the same in Tomcat as it used to in Resin. After some debuging it appeared as if the HttpSession.getLastAccessedTime() could no longer be used at this stage of the clean up. Every time you tried to access it I got a IllegalStateException.

Some searching on the web later toled me that this was because the session is already invalidated at this point. And an invalidated sessions information cannot be trusted. So what I had to do is build another listener. This time one that is more generic and catches all session deletions. The class to implement in order to do this is called the HttpSessionListener. The methods on this class are called when a session is made or destroyed.

By storing the last access time during the destruction the idle time is available.

One thought on “Cleaning Up Java Sessions

  1. Pingback: Narnio » How To Get An Accurate Session Count With Tomcat

Leave a Reply