I am only asking in threading perspective...probably answered many times but please help me to understand this.
With reference to post here Volatile Vs Static in java
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 :
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 < 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();
}
}
}
}
Output:
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
If I remove the static from the testValue, result obtained:
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
Why thread 2 is not reading the updated value? If it has to be made static , whats the use of volatile?
Can someone give link to a good example of volatile where that variable is not declare static.
Thanks