title: Java within thread reordering of instructions on the same variable
body: <p>After reading through JLS and looking through multiple scenarios I can't get quite right which rules does the Java Memory models obeys for intra-thread semantics</p>
  
  <p>Consider this code just for example purpose: </p>
  
  <pre><code>public class CharIndexer {
      public Map&lt;char, int&gt; charLastIndex;
  
      public void changeCount(String phrase) {
          Map&lt;char, int&gt; newCharLastIndex = new HashMap&lt;char, int&gt;();
  
          for (int i = 0; i &lt; s.length(); i++){
              newCharLastIndex.put(s.charAt(i),i);
          }
  
          charLastIndex = newCharLastIndex;
      }
  }
  </code></pre>
  
  <p>In a scenario with multiple threads holding a reference to the same instance of CharIndexer, reading the field charLastIndex while one of them invokes changeCount method.</p>
  
  <p>Would it be a valid reordering if the assignment to the charLastIndex field, the last assignment on the method, was done before the for block?</p>
  
  <p>This would make possible for the reading threads to see a Map which was still not populated.</p>
  
  <p>While I agree the visibility guarantee should be made explicit with a volatile keyword, do the intra-thread semantics allow such reordering? </p>
  
  <p>Single-thread execution of both orders grant the same results, but which rules do govern the intra-thread reordering that would avoid the reordering of the two for blocks in this implementation:</p>
  
  <pre><code>public class CharIndexer {
      public Map&lt;char, int&gt; charLastIndex;
  
      public void changeCount(String phrase) {
          Map&lt;char, int&gt; newCharLastIndex = new HashMap&lt;char, int&gt;();
  
          for (int i = 0; i &lt; s.length(); i++){
              newCharLastIndex.put(s.charAt(i),i);
          }
  
          // just changing values around
          foreach(Map.Entry&lt;char,int&gt; charEntry : newCharLastIndex) {
               charEntry.setValue(charEntry.getValue() * 10);
          }
  
          charLastIndex = newCharLastIndex;
      }
  }
  </code></pre>
  
  <p>I'm trying to wrap my head around how far does the JIT analysis goes or if I'm ignorant of the particular set of rules for intra-thread semantics.</p>