Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to make a static variable thread safe?

 
Rajesh Khan
Ranch Hand
Posts: 230
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can i make a static variable in a class thread safe ??
 
Tim Moores
Bartender
Posts: 2848
46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 230
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 230
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic