• Post Reply Bookmark Topic Watch Topic
  • New Topic

Are static variable and method threadsafe?

 
sura watthana
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are static variable and method threadsafe? if so Could you explain with some samples?
 
amit punekar
Ranch Hand
Posts: 544
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Static means shared across all the instances of that Class in a JVM. Shared resources are not thread-safe.Hence Static method or variables are not thread safe.
If you are talking about declaring constants using static and final keyword then because they are read-only, they are thread safe.

You have to synchronize the static method if you want thread safe nature. This requires the Thread that want to execute the static method to obtain Class level lock.


Regards,
amit
 
Stephan van Hulst
Bartender
Posts: 6586
85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thread safety is completely unrelated to specifiers like static. Thread safety depends on a lot of factors. You can easily have a static field that is thread safe by virtue of it being final and immutable. Or if your methods only ever read from it, you don't have to worry about concurrent access either.

Are static variables and methods inherently thread safe? No.
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thread safety is completely unrelated to specifiers like static


hmm a bit strong, mostly unrelated, static initialisation comes with stronger guarantees under the new memory model and I've seen that used quite a bit. So being static could help in that instance , though not make it thread safe on its own i.e. with initialisation you would have to consider its static ness in determining thread safety.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!