wood burning stoves 2.0*
The moose likes Java in General and the fly likes How to make a static variable thread safe? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to make a static variable thread safe?" Watch "How to make a static variable thread safe?" New topic
Author

How to make a static variable thread safe?

Rajesh Khan
Ranch Hand

Joined: Oct 16, 2011
Posts: 230
How can i make a static variable in a class thread safe ??
Tim Moores
Rancher

Joined: Sep 21, 2011
Posts: 2408
One approach would be to synchronize all accesses to it.

But is it even necessary? If the object is never altered after the initial creation then there's nothing to worry about.
Rajesh Khan
Ranch Hand

Joined: Oct 16, 2011
Posts: 230
Tim Moores wrote:One approach would be to synchronize all accesses to it.

But is it even necessary? If the object is never altered after the initial creation then there's nothing to worry about.

I think i need to because different servlets will access it
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4371
    
    8

But what are they doing with it? That's what matters. There's no single answer to how to make a variable thread safe without some more context.

For instance, if the variable is never being changed, then as Tim says it's already safe. However, it might be referencing an object - in which case the question is, is that object thread safe?

If the servlets are updating the value of this static variable, then you've got the possibility of conflicts. But how you fix that depends on what is happening.
Rajesh Khan
Ranch Hand

Joined: Oct 16, 2011
Posts: 230
Matthew Brown wrote:But what are they doing with it? That's what matters. There's no single answer to how to make a variable thread safe without some more context.

For instance, if the variable is never being changed, then as Tim says it's already safe. However, it might be referencing an object - in which case the question is, is that object thread safe?

If the servlets are updating the value of this static variable, then you've got the possibility of conflicts. But how you fix that depends on what is happening.


The servlets will be adding values to it. (Actually its not really servlets but jersey resources will be adding to it)
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4371
    
    8

OK, we're getting closer. Adding values to what? What sort of object is it?

If it's thread safe, no worries. If it isn't, then synchronise the bits that add the values.
 
jQuery in Action, 2nd edition
 
subject: How to make a static variable thread safe?