How can I access static variable from many thread simultaneously.
If I have a class like
Class A {
public static boolean FLG=false;
.....................
....................
}
And I need to access the value from thread 1 like
....................
public void run() {
boolean t1=A.FLG;
..................
}
and from thread 2 I need to set value like
....................
public void run() {
A.FLG=true;
..................
}
Does this cause memory violation ?. If so what is the recommended method to handle such a situation?.
Wrap the static variable in a synchronized method and call the method as you like
Note that there are other ways to synchronize access to a method. They are considered more efficient in environments busy threads accessing the same methods.
Check the ReentrantLock class. There are also answers for when to use synchronized and RentrantLock and many more information that could be found through google.
Also as
peter
's answer andmuel
's comment suggests. Marking theboolean
variable as volatile should be helpful.volatile
boolean variables will NOT cache it's initial value (false
ortrue
). The JVM could do that occasionally which could be unexpected by the programmer.You may get some undesired situation where two threads try to set different values into the static variable and you won`t have sure what exactly value really is there. The best way (thinking in a simple scenario) I think it is using AtomicBoolean ( http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicBoolean.html ) and you get the value in the object and use it (instead of using the object all the time, due a different thread can change it and you might get unexpected scenario).
Another suggestion is to use Byteman to create concurrent tests.
Regards, Luan
In Class A , you can create a set and get method for FLG like:
Now from other Threads, access value of
FLG
usng this method. This will keep the value ofFLG
Consistent across multiple Threads.If you do not want to use synchronized, ReentrantLock, you can write your own logic for this.
Example:
If all you want to do is get and set a primitive you can make it
volatile
and it will be thread safe for those operations.