简体   繁体   中英

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 (eg 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 .

我认为这取决于您使用的容器,实施问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM