title: Simplest and understandable example of volatile keyword in Java
body: <p>I'm reading about <em>volatile</em> keyword in Java and completely understand the theory part of it.</p>
  
  <p>But, what I'm searching for is, a good case example, which shows what would happen if variable wasn't <em>volatile</em> and if it were.</p>
  
  <p>Below code snippet doesn't work as expected (taken from <a href="https://stackoverflow.com/a/10764147/2546848">here</a>):</p>
  
  <pre><code>class Test extends Thread {
  
      boolean keepRunning = true;
  
      public void run() {
          while (keepRunning) {
          }
  
          System.out.println("Thread terminated.");
      }
  
      public static void main(String[] args) throws InterruptedException {
          Test t = new Test();
          t.start();
          Thread.sleep(1000);
          t.keepRunning = false;
          System.out.println("keepRunning set to false.");
      }
  }
  </code></pre>
  
  <p>Ideally, if <code>keepRunning</code> wasn't <em>volatile</em>, thread should keep on running indefinitely. But, it does stop after few seconds.</p>
  
  <p>I've got two basic questions:</p>
  
  <ul>
  <li>Can anyone explain volatile with example? Not with theory from JLS.</li>
  <li>Is volatile substitute for synchronization? Does it achieve atomicity?</li>
  </ul>