In almost all the posts I have read -
If two Threads(suppose Thread 1 and Thread 2) are accessing the same object and updating a variable which is declared as static then it means Thread 1 and Thread 2 can make their own local copy of the same object(including static variables) in their respective cache, so updating by Thread 1 to the static variable in its local cache wont reflect in the static variable for Thread 2 cache . Static variables are used in the Object Context where updating by one object would reflect in all the other objects of the same class but not in the Thread context where updating of one thread to the static variable will reflect the changes immediately to all the threads (in their local cache).
But when I run below code snippet
public class StatciVolatile3 {
public static void main(String args[]) {
new ExampleThread2("Thread 1 ").start();
new ExampleThread2("Thread 2 ").start();
}
}
class ExampleThread2 extends Thread {
private static int testValue = 1;
public ExampleThread2(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();
}
}
}
}
The output is -
Thread 1 : 0
Thread 2 : 0
Test Value T2: 2
Test Value T1: 2
Thread 2 : 1
Test Value T2: 2
Thread 1 : 1
Test Value T1: 3
Thread 2 : 2
Test Value T2: 3
Thread 1 : 2
Test Value T1: 4
As static variable is not shared among the threads so for thread 2 the test value should always be 1. But this is not the case.
I read so many other questions related to same problem but still I am not able to understand why is this happening. Could someone please help me in understanding this problem.
Thanks in advance.
I think you're being confused by the dangers of the memory model.
Static variables are shared between threads - the articles you've been reading haven't been trying to say that each thread has its own independent set of static variables. Instead, they've been trying to inform you that unprotected modification of shared state isn't guaranteed to be visible in other threads without setting up appropriate memory barriers. It's entirely fine for those changes to be visible to other threads immediately - it's just not guaranteed.
See more on this question at Stackoverflow