title: Why static variable is shared among the threads
body: <p>In almost all the posts I have read:</p>
  <p>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 won't reflect in the static variable for Thread 2 cache.</p>
  <p>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).</p>
  <p>But when I run below code snippet:</p>
  <pre><code>public class StatciVolatile3 {
  
      public static void main(String args[]) {
          new ExampleThread2(&quot;Thread 1 &quot;).start();
          new ExampleThread2(&quot;Thread 2 &quot;).start();
      }
  
  }
  
  class ExampleThread2 extends Thread {
      private static int testValue = 1;
  
      public ExampleThread2(String str) {
          super(str);
      }
  
      public void run() {
          for (int i = 0; i &lt; 3; i++) {
              try {
                  System.out.println(getName() + &quot; : &quot; + i);
                  if (getName().compareTo(&quot;Thread 1 &quot;) == 0) {
                      testValue++;
                      System.out.println(&quot;Test Value T1: &quot; + testValue);
                  }
                  if (getName().compareTo(&quot;Thread 2 &quot;) == 0) {
                      System.out.println(&quot;Test Value T2: &quot; + testValue);
                  }
                  Thread.sleep(1000);
              } catch (InterruptedException exception) {
                  exception.printStackTrace();
              }
          }
      }
  }
  </code></pre>
  <p>The output is:</p>
  <pre><code>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
  </code></pre>
  <p>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.</p>
  <p>I read so many other questions related to same problem. Why is this happening?</p>