Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Multithread Access Static Variable

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?.

like image 404
Haris Avatar asked Dec 26 '22 21:12

Haris


1 Answers

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.

like image 188
Peter Lawrey Avatar answered Jan 12 '23 07:01

Peter Lawrey