Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "volatile" mean in Java?

We use volatile in one of our projects to maintain the same copy of variable accessed by different threads. My question is whether it is alright to use volatile with static. The compiler does not give any errors but I don't understand the reason of using both.

like image 316
jnivasreddy Avatar asked Feb 03 '11 11:02

jnivasreddy


People also ask

When should I use volatile in Java?

Yes, volatile must be used whenever you want a mutable variable to be accessed by multiple threads. It is not very common usecase because typically you need to perform more than a single atomic operation (e.g. check the variable state before modifying it), in which case you would use a synchronized block instead.

What is volatile keyword used for?

The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time.

What does volatile mean in programming?

A volatile variable is a variable that is marked or cast with the keyword "volatile" so that it is established that the variable can be changed by some outside factor, such as the operating system or other software.

What is difference between volatile and static?

static variables are shared among objects under a thread? This should read static variables are shared among objects all objects regardless of threads. "volatile variables are shared among multiple threads(so objects as well)." Volatile does not change how variables are shared among multiple threads or objects.


1 Answers

Short of reading the memory model specification, I recommend you read http://jeremymanson.blogspot.com/2008/11/what-volatile-means-in-java.html. It's written by one of the JMM authors and should answer your question. Thinking of memory reads and writes in terms of the happens-before clause is also helpful; the JMM for Java 5 onwards adds happens-before semantics to volatile.

Specifically, when you read a volatile variable from one thread, all writes up to and including the write to that volatile variable from other threads are now visible to that one thread. If you have some time, there's a Google tech talk that further discusses the topic: https://code.google.com/edu/languages/#_java_memmodel.

And, yes, you can use static with volatile. They do different things.

like image 93
ide Avatar answered Sep 18 '22 07:09

ide