This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Servlets and the fly likes Thread-safe global variables Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Servlets
Reply 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!
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Thread-safe global variables
 
Similar Threads
Help w/SingleThreadModel
Mock Question about thread-safe
Singleton or Prototype for DI bean injection?
Thread Safe Instance Variables
Web Services and multithreading