Black
Black

Reputation: 5367

HttpSessionListener - GC considerations?

Tomcat doesn't have an API for accessing the collection of active sessions, so I'd like to design an HttpSessionListener for my WebApp, but I have a few concerns around implementation.

If my listener has a member-variable List that stores references to the Sessions themselves and removes them on sessionDestroyed - does this risk a memory leak, as if that list got out of synch with Tomcat's internal tracking of Sessions, they wouldn't be able to be GCed?

For some reason this just seems like a bad idea, I'd like to know why does Tomcat not give access to it's internal list? It would be extremely useful. Any insights would be appreciated.

Upvotes: 2

Views: 203

Answers (1)

Mark Olsson
Mark Olsson

Reputation: 320

I've found that as long as you implement sessionCreated and sessionDestroyed, it's completely reliable. The only downside is you will lose active sessions Tomcat knows about if your app isn't running or when it's restarted, but I've never seen it miss out on getting a created or destroyed notice.

Make sure you are storing the session data in something that handles concurrency, like a ConcurrentHashMap.

Here's a simple example:

public class SessionData implements HttpSessionListener {
    private final static Map<String, HttpSession> activeSessions = new ConcurrentHashMap<>();

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        if (session != null) {
            String id = session.getId();
            System.out.println("HTTP session created. ID: " + id);
            activeSessions.put(id, session);
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        if (session != null) {
            String id = session.getId();
            System.out.println("HTTP session destroyed. ID: " + id);
            activeSessions.remove(id);
        }
    }
}

Upvotes: 1

Related Questions