title: Using ThreadLocal in tandem with Volatile gives unpredictable results
body: <p>I was reading through Java Memory model and was playing with volatile. I wanted to check how Volatile will work in tandem with ThreadLocal. As per definition ThreadLocal has its own, independently initialized copy of the variable whereas when you use volatile keyword then JVM guarantees that all writes and subsequent reads are done directly from the memory. Based on the high level definitions i knew what i was trying to do will give unpredictable results. But just out of curiosity wanted to ask if someone can explain in more details as if what is going on in the background. Here is my code for your reference...</p>
  
  <pre><code>public class MyMainClass {
  
      public static void main(String[] args) throws InterruptedException {
  
          ThreadLocal&lt;MyClass&gt; local = new ThreadLocal&lt;&gt;();
          local.set(new MyClass());
  
          for(int i=0;i&lt;5; i++){
              Thread thread = new Thread(local.get());
              thread.start();
          }
  
      }
  
  }
  
  
  public class MyClass implements Runnable {
  
      private volatile boolean flag = false;
  
      public void printNameTillFlagIsSet(){
          if(!flag)
          System.out.println("Flag is on for : " + Thread.currentThread().getName());
          else
              System.out.println("Flag is off for : " + Thread.currentThread().getName());
      }
  
  
      @Override
      public void run() {
          printNameTillFlagIsSet();
          this.flag = true;       
      }
  
  
  }
  </code></pre>