Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Declaring a <strong>static</strong> variable in Java, means that there will be only one copy, no matter how many objects of the class are created. The variable will be accessible even with no <code>Objects</code> created at all. However, threads may have locally cached values of it.</p> <p>When a variable is <strong>volatile</strong> and not <strong>static</strong>, there will be one variable for each <code>Object</code>. So, on the surface it seems there is no difference from a normal variable but totally different from <strong>static</strong>. However, even with <code>Object</code> fields, a thread may cache a variable value locally.</p> <p>This means that if two threads update a variable of the same Object concurrently, and the variable is not declared volatile, there could be a case in which one of the thread has in cache an old value.</p> <p>Even if you access a <strong>static</strong> value through multiple threads, each thread can have its local cached copy! To avoid this you can declare the variable as <strong>static volatile</strong> and this will force the thread to read each time the global value.</p> <p>However, <strong>volatile</strong> is not a substitute for proper synchronisation!<br> For instance:</p> <pre><code>private static volatile int counter = 0; private void concurrentMethodWrong() { counter = counter + 5; //do something counter = counter - 5; } </code></pre> <p>Executing <code>concurrentMethodWrong</code> concurrently many times may lead to a final value of counter different from zero!<br> To solve the problem, you have to implement a lock:</p> <pre><code>private static final Object counterLock = new Object(); private static volatile int counter = 0; private void concurrentMethodRight() { synchronized (counterLock) { counter = counter + 5; } //do something synchronized (counterLock) { counter = counter - 5; } } </code></pre> <p>Or use the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html" rel="noreferrer"><code>AtomicInteger</code></a> class.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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