Session counter with HttpSessionListener and session count variable access

后端 未结 2 1939
走了就别回头了
走了就别回头了 2021-01-29 01:04

I saw an example with session counter in Sun\'s \"Core Servlets and JavaServer Pages vol 2\".
Counter is simply build on HttpSessionListener and increments/decr

相关标签:
2条回答
  • 2021-01-29 01:22

    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.

    0 讨论(0)
  • 2021-01-29 01:22

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题