title: Java Memory Model: Mixing unsynchronized and synchronized
body: <p>Suppose there is a class like this:</p>
  
  <pre><code>public void MyClass {
      private boolean someoneTouchedMeWhenIWasWorking;
  
      public void process() {
          someoneTouchedMeWhenIWasWorking = false;
          doStuff();
          synchronized(this) {
              if (someoneTouchedMeWhenIWasWorking) {
                  System.out.println("Hey!");
              }
          }
      }
  
      synchronized public void touch() {
          someoneTouchedMeWhenIWasWorking = true;
      }
  }
  </code></pre>
  
  <p>One thread calls <code>process</code>, another calls <code>touch</code>. Note how <code>process</code> clears the flag without synchronization when it starts.</p>
  
  <p>With Java memory model, is it ever possible that the thread running <code>process</code> will see the effect of its local, unsynchronized write, even though <code>touch</code> happened later?</p>
  
  <p>That is, if the threads execute in this order:</p>
  
  <pre><code>T1: someoneTouchedMeWhenIWasWorking = false; // Unsynchronized
  T2: someoneTouchedMeWhenIWasWorking = true; // Synchronized
  T1: if (someoneTouchedMeWhenIWasWorking) // Synchronized
  </code></pre>
  
  <p>... is it ever possible that T1 would see the value from its local cache? Can it flush what it has to memory first (overriding whatever T2 has written), and reload that value from memory?</p>
  
  <p>Is it necessary to synchronize the first write or make the variable volatile?</p>
  
  <p>I would really appreciate it if the answers were backed by documentation or some respectable sources.</p>