Note that there are some explanatory texts on larger screens.

plurals
  1. POStatic variable vs Volatile
    text
    copied!<p>I am only asking in threading perspective...probably answered many times but please help me to understand this.</p> <p>With reference to post here <a href="https://stackoverflow.com/questions/2423622/volatile-vs-static-in-java">Volatile Vs Static in java</a></p> <p>asking a static variable value is also going to be one value for all threads, then why should we go for volatile? I found following example :</p> <pre><code>public class VolatileExample { public static void main(String args[]) { new ExampleThread("Thread 1 ").start(); new ExampleThread("Thread 2 ").start(); } } class ExampleThread extends Thread { private static volatile int testValue = 1; public ExampleThread(String str){ super(str); } public void run() { for (int i = 0; i &lt; 3; i++) { try { System.out.println(getName() + " : "+i); if (getName().compareTo("Thread 1 ") == 0) { testValue++; System.out.println( "Test Value T1: " + testValue); } if (getName().compareTo("Thread 2 ") == 0) { System.out.println( "Test Value T2: " + testValue); } Thread.sleep(1000); } catch (InterruptedException exception) { exception.printStackTrace(); } } } } </code></pre> <p>Output:</p> <pre><code>Thread 1 : 0 Test Value T1: 2 Thread 2 : 0 Test Value T2: 2 Thread 1 : 1 Test Value T1: 3 Thread 2 : 1 Test Value T2: 3 Thread 1 : 2 Test Value T1: 4 Thread 2 : 2 Test Value T2: 4 </code></pre> <p>If I remove the static from the testValue, result obtained:</p> <pre><code>Thread 1 : 0 Test Value T1: 2 Thread 2 : 0 Test Value T2: 1 Thread 1 : 1 Test Value T1: 3 Thread 2 : 1 Test Value T2: 1 Thread 1 : 2 Test Value T1: 4 Thread 2 : 2 Test Value T2: 1 </code></pre> <p>Why thread 2 is not reading the updated value? If it has to be made static , whats the use of volatile?</p> <p>Can someone give link to a good example of volatile where that variable is not declare static.</p> <p>Thanks </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