Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Volatile variable as you have read guarantees visibility but doesn't guarantee atomicity - another important aspect of thread safety. I will try to explain by an example</p> <pre><code>public class Counter { private volatile int counter; public int increment() { System.out.println("Counter:"+counter); // reading always gives the correct value return counter++; // atomicity isn't guaranteed, this will eventually lead to skew/error in the expected value of counter. } public int decrement() { System.out.println("Counter:"+counter); return counter++; } } </code></pre> <p>In the example, you can see that the read operation will always give the correct value of counter at an instant of time, however atomic operations (like evaluate a condition and do something and read and write on the basis of read value) thread safety is not guaranteed.</p> <p>You can refer <a href="https://stackoverflow.com/questions/7851327/illustrating-volatile-is-this-code-thread-safe">this</a> answer for additional details.</p> <blockquote> <p>Volatile means each Thread Access the variable will have its own private copy which is same as original one.But if the Thread is going to change that private copy,then original one will not get reflected.</p> </blockquote> <p>I am not sure I understand you correctly, but volatile fields imply they are read and written from the main memory accessible to all threads - there are no thread specific copies (caching) of the variable.</p> <p>From <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.4" rel="nofollow noreferrer">JLS</a>,</p> <blockquote> <p>A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload