title: Why is i++ not atomic?
body: <p>Why is <code>i++</code> not atomic in Java?</p>
  
  <p>To get a bit deeper in Java I tried to count how often the loop in threads are executed.</p>
  
  <p>So I used a</p>
  
  <pre><code>private static int total = 0;
  </code></pre>
  
  <p>in the main class.</p>
  
  <p>I have two threads.</p>
  
  <ul>
  <li>Thread 1: Prints <code>System.out.println("Hello from Thread 1!");</code></li>
  <li>Thread 2: Prints <code>System.out.println("Hello from Thread 2!");</code></li>
  </ul>
  
  <p>And I count the lines printed by thread 1 and thread 2. But the lines of thread 1 + lines of thread 2 don't match the total number of lines printed out.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
  import java.util.logging.Level;
  import java.util.logging.Logger;
  
  public class Test {
  
      private static int total = 0;
      private static int countT1 = 0;
      private static int countT2 = 0;
      private boolean run = true;
  
      public Test() {
          ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
          newCachedThreadPool.execute(t1);
          newCachedThreadPool.execute(t2);
          try {
              Thread.sleep(1000);
          }
          catch (InterruptedException ex) {
              Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
          }
          run = false;
          try {
              Thread.sleep(1000);
          }
          catch (InterruptedException ex) {
              Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
          }
          System.out.println((countT1 + countT2 + " == " + total));
      }
  
      private Runnable t1 = new Runnable() {
          @Override
          public void run() {
              while (run) {
                  total++;
                  countT1++;
                  System.out.println("Hello #" + countT1 + " from Thread 2! Total hello: " + total);
              }
          }
      };
  
      private Runnable t2 = new Runnable() {
          @Override
          public void run() {
              while (run) {
                  total++;
                  countT2++;
                  System.out.println("Hello #" + countT2 + " from Thread 2! Total hello: " + total);
              }
          }
      };
  
      public static void main(String[] args) {
          new Test();
      }
  }
  </code></pre>