| 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!
|
 |
 |
|
|
subject: Thread-safe global variables
|
|
|