title: Java concurrency: weird output
body: <p>I'm fooling around with Java threads and I wrote this little program that creates several threads and runs them. In each thread a value is incremented multiple times. I used ThreadLocal class so that there's no contention for resources.</p>
  
  <p>Source:</p>
  
  <pre><code>class MyValueHolder {
  
      public static ThreadLocal&lt;Integer&gt; value = new ThreadLocal&lt;Integer&gt;()
      {
          protected Integer initialValue() {
              return 0;
          }
      };
  
      public static void increment() {
          value.set(value.get() + 1);
      }
  
      public static Integer get() {
          return value.get();
      }
  }
  
  class MyTask implements Runnable {
  
      public static int counter;
  
      public MyTask() {
          counter++;
      }
  
      public void run() {
  
          for(int i = 0; i &lt; 100; i++) {
              MyValueHolder.increment();
          }
          System.out.println("MyTask " + counter + ", Value " + MyValueHolder.get());
      }
  }
  
  public class Main {
  
      public static void main(String[] args) {
  
          ExecutorService es = Executors.newCachedThreadPool();
  
          for(int i = 0; i &lt; 5; i++) {
  
              es.execute(new MyTask());
          }
  
          es.shutdownNow();
      }
  }
  </code></pre>
  
  <p>After completion the output is most of the time this:</p>
  
  <pre><code>MyTask 5, Value 100
  MyTask 5, Value 100
  MyTask 5, Value 100
  MyTask 5, Value 100
  MyTask 5, Value 100
  </code></pre>
  
  <p>Which is what I'd expect to see.</p>
  
  <p>However, sometimes I get something like this:</p>
  
  <pre><code>MyTask 2, Value 100
  MyTask 4, Value 200
  MyTask 5, Value 300
  MyTask 5, Value 100
  MyTask 5, Value 100
  </code></pre>
  
  <p>Now this is confusing. Why do the values differ even though each task does absolutely the same thing?</p>