wood burning stoves 2.0*
The moose likes Servlets and the fly likes Thread-safe global variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Thread-safe global variables" Watch "Thread-safe global variables" New topic
Author

Thread-safe global variables

Ali Ekber
Ranch Hand

Joined: Jun 12, 2005
Posts: 41
Can anyone pls tell me how to declare thread-safe global variables in a servlet? Thanks.
Sharad Agarwal
Ranch Hand

Joined: Sep 11, 2002
Posts: 167
You could make their access thread-safe by adding synchronization.


Alco-Haul: We move spirits.
Demented Deliberations of a Dilettante
Ali Ekber
Ranch Hand

Joined: Jun 12, 2005
Posts: 41
But if you declare the variables in the synchronized block, they will be local varibles. If you declare it out side the synchronized block, will they be thread-safe, even if you assig values inside the synchronized block? Thanks.
Sharad Agarwal
Ranch Hand

Joined: Sep 11, 2002
Posts: 167
Originally posted by Ali Ekber:
But if you declare the variables in the synchronized block, they will be local varibles. If you declare it out side the synchronized block, will they be thread-safe, even if you assig values inside the synchronized block? Thanks.


The amswer to your last question is 'yes'. Please allow me to elaborate. Add synchronization blocks around the code that accesses the variables, and not the declaration. The declaration remains global (class member variable). But, when the variable is accessed, we force the different threads to stand in line and do their thing in sequence.
Ali Ekber
Ranch Hand

Joined: Jun 12, 2005
Posts: 41
Ah! Now I got it. Thanks alot!
 
Consider Paul's rocket mass heater.
 
subject: Thread-safe global variables