aspose file tools*
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes Synchronizing Session Counter Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Synchronizing Session Counter" Watch "Synchronizing Session Counter" New topic
Author

Synchronizing Session Counter

A Phatak
Greenhorn

Joined: Sep 22, 2011
Posts: 24
I keep having some trouble understanding synchronizing concept in the context of static vs nonstatic. For e.g. take a look at the code below:


It is a simple listener that counts number of active sessions. However, we know HttpSession object is not thread safe. So I believe that "counter" variable should be incremented in a "synchronized" manner.

It is clear that getCounter() should change to public synchronized static int getSessionCounter()

My question is what changes should be implemented in sessionDestroyed() and sessionCreated() methods? Which of the following is correct?



OR




Or does it have to be synchronized at all?


ocpjp 6 (86%)
A Phatak
Greenhorn

Joined: Sep 22, 2011
Posts: 24
Sorry if this is a wrong place for this question? I am studying for the OCEWCD and thought this is my forum. If not please redirect me appropriately
Frits Walraven
Creator of Enthuware JWS+ V6
Bartender

Joined: Apr 07, 2010
Posts: 1529
    
  22

Hi Phatak

Sorry if this is a wrong place for this question? I am studying for the OCEWCD and thought this is my forum. If not please redirect me appropriately

It is perfectly ok to ask a question regarding threads over here although this topic belongs to the basic concepts of OCPJP you still need to know about it in OCEWCD.

Every object (or instance) has one lock and every class has exactly one lock. Locking on static methods (accessing static data) is usually done on the class, where locking instance methods is mostly done on the instance (this()).

As there is only one listener object per listener declaration in the web-container (the container will instantiate your listener) you can also give the listener a private instance variable holding a counter. So counting the sessions in the listener class instance variable will have the same effect as counting the sessions in a static variable.

So these two implementations will both work:

Locking on the classLocking on this()

Regards,
Frits
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronizing Session Counter
 
Similar Threads
HttpSessionListener custom methodsin HFSJ page 259
Session Counter Locking Question
HttpSessionListener : Where can i see this output ?
how would the sessionListener object be accessed
Updating a JSP session attribute and html code on mouse click