title: Http Sessions life cycle in Tomcat
body: <p>I have a task to show to the site admin a list of user names and how many tomcat sessions are currently utilized by each user (along with some other support-related information).</p>
  
  <p>I keep authenticated users as the application context attribute as follows (sparing unnecessary details).</p>
  
  <pre><code>Hashtable&lt;String, UserInfo> logins //maps login to UserInfo</code></pre>
  
  <p>where UserInfo is defined as</p>
  
  <pre><code>class UserInfo implements Serializable {
  String login;
  private transient Map&lt;HttpSession, String> sessions = 
        Collections.synchronizedMap(
               new WeakHashMap&lt;HttpSession, String>() //maps session to sessionId
        );
  ...
  }
  </code></pre>
  
  <p>Each successful login stores the session into this <code>sessions</code> map.
  My <code>HttpSessionsListener</code> implementation in <code>sessionDestroyed()</code> removes the destroyed session from this map and, if sessions.size() == 0, removes UserInfo from <code>logins</code>.</p>
  
  <p>From time to time I have 0 sessions showing up for some users. Peer reviews and unit testing show that the code is correct. All sessions are serializable.</p>
  
  <p>Is it possible that Tomcat offloads sessions from memory to the hard drive, e.g. when there is a period of inactivity (session timeout is set to 40 minutes)? Are there any other scenarios where sessions are 'lost' from GC point of view, but HttpSessionsListener.sessionDestroyed() wasn't invoked?</p>
  
  <p>J2SE 6, Tomcat 6 or 7 standalone, behaviour is consistent on any OS.</p>