What's the lifecycle of a Java HttpSession object?

Obviously at some point an object is created and destroyed/returned to pool. I'm especially interested in how these are garbage-collected. Is there any way to control this behavior? Specifically, will a call to invalidate() mark these objects for collection? When do they release any references stored in them?

The more detail the better.


HttpSession is basically a map from string key to some arbitrary value. Every time you create a session (by accessing JSP or calling getSession()/getSession(true)), the container will generate unique string session ID and hold a reference to that HttpSession object. Again, it will use a map from session ID to HttpSession object.

Once you put something in the session, the container holds a reference to that session and the session holds a reference to your object. It will stay there for some time. There are three situation when your item will be removed from the session:

  1. When you explicitly remove it (removeAttribute() or setAttribute(null))

  2. When you invalidate() the whole session. This basically removes all attributes and removes the whole session from container-managed session map

  3. When the session expires (same behaviour as with 2.) This happens when no servlet/JSP accessed session in configurable amount of time (e.g. 10 minutes)

The moment an object is removed from the session (any of the points above) and no other code holds a reference to that object, it is eligible for garbage collection and will be removed during next GC run.

You can add an object that implements HttpSessionBindingListener to an HttpSession to observe some of the behaviour described above. An object that implements this interface could, for example, print a log message when it is unbound from the session.

You can check out the documentation here.

I think this depends on the container you use, the question of implementation.

Need Your Help

Swift - create a fixed length array enforced at compile time

ios swift tuples compile-time

I want to enforce (compile time) array with 5 elements of a particular type

Most efficient way to import data from one MySQL database to another

mysql import load-data-infile

I'm writing a PHP script which imports data from tables in two different databases into another one. I've got it working ok with sample data, except now I've moved to using data closer resembling its