This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Threadsafe 'static variable'  RSS feed

 
Anil Sharma
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

How will we be make static variables of a class to threadsafe?
 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't. If it's part of your public API & it is not final, I can change its value.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sure you can. One possibility is the one Pho Tek gave: use a final variable. Preferably it should be either a primitive type or a reference to an immutable instance. Another possibility, however, is to let the variable be non-final, and private - and then make sure that every time you access the variable, it is either (a) inside a static synchronized method, or (b) inside a synchronized block which is synchronized on MyClass.class, where MyClass is the name of the class that contains the static variable. Or (c) every access could be made within a synchronized block which is synchronized on some other instance, such that every one of these synchronized blocks uses the same instance. There are other ways thread-safety might be achieved as well, depending on what you need to do with the variable - but using synchronization is probably the most common, straightforward way to do it.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wondered about this for a bit and you have to figure out what you mean by safe. That is, for what scope. If you want to call three methods on an object that all use the static variable and you don't want another thread to change the value in that time span, three synchronized methods won't help. You'll have to synchronize on something for the whole time. And you'll have to trust every other thread to synchronize on the same thing.

It might be hard to find something to synchronize on. Wonder if this sucks too much ...

where the other class might do:
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!