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:[EMAIL PROTECTED] > Sent: Tuesday, August 12, 2003 10:21 AM > To: [EMAIL PROTECTED] > 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--; > } > --------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]