Reputation: 3736
Suppose I have a Java web application and I set my session time-out to 10 minutes. I also have a Collection<HttpSession>
in my servlet context which stores all currently existing sessions (ignore the non/usefulness of this collection). With this setup, can a Session object actually expire? The collection will live throughout the entire application's lifetime, holding a reference to each session.
Upvotes: 1
Views: 996
Reputation: 4695
It's not clear why you, as a web developer, are maintaining the sessions in a collection when web container does something similar (and more). Since you usually request the session from the container via the HttpServletRequest
object, even if you maintained another reference to it (so as to perhaps prevent it from garbage collection), the web container has no knowledge of it, so the session will expire (in the most straightforward sense of the word).
If a session DOES expire, then what happens if I try to access the session at a later time?
A web container, like Tomcat, maintains a session for requests. Considering that cookies are managing the sessions, every request will send the same cookies to the same server, so the web container arranges for finding the session and returning it to you from the request object. See getSession() API. Here, based on the value of the argument, you can request new or existing session from the web container.
Do I get a(n) (null pointer) Exception?
Maybe. See the API above (the boolean argument, getSession
is overloaded).
Or could the session already be recycled and thus I'm not accessing the session I think I was?
Yes, that is entirely possible. If the session expires (e.g. after some inactivity), since you asked the web container to expire it, you have lost it (so to speak).
If a session CAN NO LONGER EXPIRE, what can I do to remedy this?
That is rather strange, however it may be possible based on web container implementation. All web containers (should) provide a configuration that helps configure the default session timeout (and I think servlet spec provides the default value). It is rather unsafe to have no expiry on session timeouts. Check the documentation of your web container to see how to configure this. There should be a way to limit the session's validity.
Does this behaviour differ for each different servlet container env(tomcat, jboss, jetty...) or is it more or less consistent?
The idea of sessions and session timeouts are the same across containers since it relates to HTTP and it is part of the servlet spec. Every container has its documentation to configure its default session timeout.
Upvotes: 1