File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
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!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread-safe global variables
 
Similar Threads
Thread Safe Instance Variables
Web Services and multithreading
Help w/SingleThreadModel
Singleton or Prototype for DI bean injection?
Mock Question about thread-safe