I use the servlet context to hold details of logged in users in a hash map. How can I clear the user id of a user who is idle after 20 minutes?
4 Answers
Probably you could set the Session Timeout to 20 minutes for the application, and make sure that each user has a active session, which also contains the user id. If the user goes idle for 20 minutes, then the session will be destroyed.
Then, you can write a HttpSessionListener to get called when a session gets destroyed. From that you can get the user id (which you already stored before, probably when the user logged in), and remove it also from your HashMap with in the SessionContext.

- 6,840
- 3
- 46
- 63
Use servlet session management for invalidating the sessions. This below snippet in web.xml will invalidate the session if idle for 20 mins.
<session-config><session-timeout>20</session-timeout></session-config>
Implement javax.servlet.http.HttpSessionListener.sessionCreated() to get a callback when a session is created. Add this session id to the servlet context using
List<String> users = HttpSessionEvent.getSession().getServletContext().getAttribute("users");
users.add(session.getId());
Implement javax.servlet.http.HttpSessionListener.sessionDestroyed() which gets a callback when a session is destroyed. Remove this session from the servlet context using
List<String> users = HttpSessionEvent.getSession().getServletContext().getAttribute("users");
users.remove(session.getId());

- 15,200
- 2
- 46
- 50
-
This works fine for session but in my opinion this will not work for servlet context – dean Jun 01 '11 at 11:09
-
Sorry, What does not work with servlet context. Can you elaborate. – Ramesh PVK Jun 01 '11 at 11:12
The simplest way is to implement ServletContextListener
, in contextInitialized()
start a thread that will do the work. in contextDestroyed
shudown the thread. The Map should be threadsafe: synchronized or Concurrent.

- 28,647
- 6
- 40
- 53
-
Why a timer, when container can give u a callback when the session is idle. – Ramesh PVK Jun 01 '11 at 11:15
-
You are right, i miss-interpreted the question. The timer is not needed at all. – Op De Cirkel Jun 01 '11 at 11:32