Session counter with HttpSessionListener and session count variable access

北战南征 提交于 2019-12-02 09:39:07

The specification of Servlet 3.0 says (§ 11.5):

Listener Instances and Threading

[...]

The container is not required to synchronize the resulting notifications to attribute listener classes. Listener classes that maintain state are responsible for the integrity of the data and should handle this case explicitly.

So no, the code is not safe. Using an AtomicCounter or synchronizing the access to the counter fixes it.

Making it volatile doean't make it safer, because ++ is not an atomic operation. So every other thread will see the new value thanks to volatile, but you might still miss increments due to a race condition reading, then incrementing the counter in parallel.

This would be safe.

public class HttpSessionListenerTest implements HttpSessionListener {
    final private AtomicInteger sessionCount = new AtomicInteger(0);

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        sessionCount.incrementAndGet();
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        sessionCount.decrementAndGet();
    }

    public int getTotalSessionCount() {
        return sessionCount.get();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!