tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Ralph Einfeldt" <ralph.einfe...@uptime-isc.de>
Subject RE: HttpSessionListener: Negative session count
Date Tue, 12 Aug 2003 08:32:22 GMT
You have to synchronize the -- and ++ operations.
Otherwise you will have unpredictable results.

You have to keep in mind that activeSessions++
is not atomic, so another thread can get between
the computation of the value and the assignment.

One scenario:
Thread A: read activeSessions = 0
Thread B: read activeSessions = 0
Thread A: compute activeSessions + 1= 1
Thread B: compute activeSessions + 1= 1
Thread A: store the result in activeSessions = 1
Thread B: store the result in activeSessions = 1

Now activeSessions is 1 although 2 Sessions are active.
If the sessions are not destroyed in a very close gap
the result will get negative.

> -----Original Message-----
> From: Christian Hauser [mailto:c.hauser@active.ch]
> Sent: Tuesday, August 12, 2003 10:21 AM
> To: tomcat-user@jakarta.apache.org
> Subject: HttpSessionListener: Negative session count
> 
> 
>    public class SessionCounter implements HttpSessionListener {
> 
>      /** Static variable to keep track of the current number 
> of active 
> sessions. */
>      private static int activeSessions = 0;
> 
>      public void sessionCreated(HttpSessionEvent event) {
>        activeSessions++;
>      }
> 
>      public void sessionDestroyed(HttpSessionEvent event) {
>        activeSessions--;
>      }
> 

Mime
View raw message