1

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?

artbristol
  • 30,694
  • 5
  • 61
  • 93
dean
  • 79
  • 1
  • 2
  • 8

4 Answers4

2

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.

Yohan Liyanage
  • 6,282
  • 2
  • 42
  • 62
1

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());
Ramesh PVK
  • 14,700
  • 2
  • 43
  • 49
0
  • Schedule a job from ServletContextListener
  • use remove() method of HashMap simply , make sure about concurrency
jmj
  • 225,392
  • 41
  • 383
  • 426
0

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.

Op De Cirkel
  • 26,245
  • 6
  • 37
  • 52