title: Synchronization on immutable objects (in java)
body: <p><strong>Code snippet - 1</strong></p>
  
  <pre><code>class RequestObject implements Runnable
  {
      private static Integer nRequests = 0;
  
      @Override
      public void run()
      {       
          synchronized (nRequests)
          {
              nRequests++;
          }
      }
  }
  </code></pre>
  
  <p><strong>Code snippet - 2</strong></p>
  
  <pre><code>public class Racer implements Runnable
  {
      public static Boolean won = false;    
  
      @Override
      public void run()
      {
          synchronized (won)
          {
              if (!won)
              won = true;
          }
      }        
  }
  </code></pre>
  
  <p>I was having a race condition with the first code snippet. I <a href="https://stackoverflow.com/q/18030502/134387">understood</a> that this was because I was obtaining a lock on an immutable object(of type Integer).</p>
  
  <p>I have written a second code snippet which is again impervious to 'Boolean' being immutable. But this works(no race condition is displayed in an output run). If I have understood the solution to my <a href="https://stackoverflow.com/q/18030502/134387">previous question</a> properly the below is is one possible way in which things can go wrong</p>
  
  <ol>
  <li>Thread 1 gets a lock on an object(say A) pointed by <code>won</code></li>
  <li>Thread 2 tries to now get a lock on the object pointed to by <code>won</code> and gets in the wait queue for A</li>
  <li>Thread 1 goes into the synchronized block, verifies that A is false and creates a new object(say B) by saying <code>won = true</code>(A thinks it won the race). </li>
  <li>'won' now points to B. Thread 1 releases the lock on object A(no longer pointed to by <code>won</code>)</li>
  <li>Now, thread-2 which was in the wait queue of object A gets woken up and gets a lock on object A which is still <code>false</code>(immutably so). It now goes into the synchronized block and assumes that it has also won, which is not correct.</li>
  </ol>
  
  <p>Why is the second code snippet working fine all the time??</p>