Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The problem is that the ++ is not atomic. The code should use <code>AtomicInteger</code> instead. With the <code>static</code> variable, both threads are trying to update the same value and the ++ is actually 3 operations: get, +1, and store. This means that there is a race condition between both of the threads and they are overwriting each other.</p> <blockquote> <p>Why thread 2 is not reading the updated value? If it has to be made static , whats the use of volatile?</p> </blockquote> <p><code>static</code> and <code>volatile</code> do different things. <code>static</code> makes the field associated with the class as opposed to the object instance. <code>volatile</code> forces any read or write of the field to cross a memory barrier. This allows multiple threads to read and update a common field but this does <em>not</em> protected you from multiple operations. If you make the variable <em>not</em> be static then you would not need the <code>volatile</code> since each thread would be working with it's own instance of the field.</p> <p>You should use <code>AtomicInteger</code>. This wraps a <code>volatile int</code> but also provides special handling of increment operations:</p> <pre><code>private static AtomicInteger testValue = new AtomicInteger(1); ... testValue.incrementAndGet(); </code></pre> <blockquote> <p>Can someone give link to a good example of volatile where that variable is not declare static.</p> </blockquote> <p>You would need a <code>volatile</code> on a non-static field when it was shared by multiple threads. For example, if you moved the <code>testValue</code> up into the <code>VolatileExample</code> class and then passed the same instance of the <code>VolatileExample</code> class into both threads so they could access <code>testValue</code>.</p>
    singulars
    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