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