Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In this case, when tou removed the <code>static</code> modifier you changed the variable, because now, each <code>ExampleThread</code> has its own <code>testValue</code>, for that, the storage value is different for each thread instance.</p> <p>Meaning of <code>static</code> modifier:</p> <blockquote> <p>Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable...</p> </blockquote> <p>Reference: <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html" rel="nofollow">Understanding Instance and Class Members</a></p> <p>About <code>volatile</code>, if you try a different kind of test, moving the <code>testValue</code> variable to the class <code>VolatileExample</code>, like this:</p> <pre><code> public class VolatileExample { private volatile int testValue = 1; ... } </code></pre> <p>Then, remove the <code>testVariable</code> from <code>ExampleThread</code> and run the code. Its output should be like the first one.</p> <p>Meaning of <code>volatile</code> modifier:</p> <blockquote> <p>Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads</p> </blockquote> <p>Reference: <a href="http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html" rel="nofollow">Atomic Access</a></p>
 

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