tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Christian Hauser <c.hau...@active.ch>
Subject Re: HttpSessionListener: Negative session count
Date Tue, 12 Aug 2003 08:44:05 GMT
Thank you Ralph

So I should use the following:

   public void sessionCreated(HttpSessionEvent event) {
     synchronized (this) {
       activeSessions++;
     }
   }

   public void sessionDestroyed(HttpSessionEvent event) {
     synchronized (this) {
       if (activeSessions > 0) {
         activeSessions--;
       }
     }
   }


Ralph Einfeldt wrote:

> 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.



Mime
View raw message