Elegantly checking whether a HTTPSession reference is still valid
I'm storing all established HTTPSession objects in a hash-map. Is there anyway of determining whether a HTTPSession is still valid before en-queuing a message?
Example: if I am iterating over the hash- map, I only want to enqueue messages for HTTPSession objects that are valid.
UPDATE
If anyone is interested, I needed this logic with the use of gwt-comet. The solution (as Tomasz Nurkiewicz pointed out) c开发者_如何学Pythonan be found at the bottom this page.
Unfortunately there is no explicit API for this. But it is easy to workaround in clean and elegant manner.
Implement HttpSessionListener
storing every newly created session in a concurrent map and removing it when session is destroyed. This way your map will always contain only valid sessions. Much cleaner, don't you think?
public class SessionStoringListener implements HttpSessionListener {
private Map<String, HttpSession> sessions = new ConcurrentHashMap<String, HttpSession>();
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent)
{
HttpSession session = httpSessionEvent.getSession();
sessions.put(session.getId(), session);
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent)
{
sessions.remove(httpSessionEvent.getSession().getId());
}
}
精彩评论