title: Concurrency, object visibility
body: <p>I'm trying to figure out if the code below suffers from any potential concurrency issues. Specifically, the issue of visibility related to volatile variables. <em>Volatile</em> is defined as: <strong>The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory"</strong></p>
  
  <pre><code>public static void main(String [] args)
  {
      Test test = new Test();
  
      // This will always single threaded
      ExecutorService ex = Executors.newSingleThreadExecutor();
  
      for (int i=0; i&lt;10; ++i)
          ex.execute(test);
  }
  
  private static class Test implements Runnable {
      // non volatile variable in question
      private int state = 0;
  
      @Override
      public void run() {
          // will we always see updated state value? Will updating state value
          // guarantee future run's see the value?
          if (this.state != -1)
              this.state++;
      }
  }
  </code></pre>
  
  <p>For the above <strong>single threaded executor</strong>:</p>
  
  <p>Is it okay to make <em>test.state</em> non volatile? In other words, will every successive <em>Test.run()</em> (which will occur sequentially and not concurrently because again executor is single threaded), always see the updated <em>test.state</em> value? If not, doesn't exiting of <em>Test.run()</em> ensure any changes made thread locally get written back to main memory? Otherwise when does changes made thread locally get written back to main memory if not upon exiting of the thread?</p>