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:
When you explicitly remove it (removeAttribute() or setAttribute(null))
When you invalidate() the whole session. This basically removes all attributes and removes the whole session from container-managed session map
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.