Return-Path: Mailing-List: contact tomcat-user-help@jakarta.apache.org; run by ezmlm Delivered-To: mailing list tomcat-user@jakarta.apache.org Received: (qmail 48139 invoked from network); 12 Aug 2003 08:39:01 -0000 Received: from mail03b.hostcenter.com (195.186.64.157) by daedalus.apache.org with SMTP; 12 Aug 2003 08:39:01 -0000 Received: from www.tim-group.com (195.186.81.200) by mail03b.hostcenter.com (RS ver 1.0.86vs) with SMTP id 0543137543 for ; Tue, 12 Aug 2003 10:39:03 +0200 (CEST) Message-ID: <3F38A8D5.6060008@active.ch> Date: Tue, 12 Aug 2003 10:44:05 +0200 From: Christian Hauser User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 X-Accept-Language: en-us, en MIME-Version: 1.0 To: Tomcat Users List Subject: Re: HttpSessionListener: Negative session count References: In-Reply-To: Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit X-Loop-Detect: 1 X-Spam-Rating: daedalus.apache.org 1.6.2 0/1000/N 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.