title: Is id = 1 - id atomic?
body: <p>From page 291 of OCP Java SE 6 Programmer Practice Exams, question 25:</p>
  
  <pre><code>public class Stone implements Runnable {
      static int id = 1;
  
      public void run() {
          id = 1 - id;
          if (id == 0) 
              pick(); 
          else 
              release();
      }
  
      private static synchronized void pick() {
          System.out.print("P ");
          System.out.print("Q ");
      }
  
      private synchronized void release() {
          System.out.print("R ");
          System.out.print("S ");
      }
  
      public static void main(String[] args) {
          Stone st = new Stone();
          new Thread(st).start();
          new Thread(st).start();
      }
  }
  </code></pre>
  
  <p>One of the answers is:</p>
  
  <blockquote>
    <p>The output could be <code>P Q P Q</code></p>
  </blockquote>
  
  <p>I marked this answer as correct. My reasoning:</p>
  
  <ol>
  <li>We are starting two threads. </li>
  <li>First one enters <code>run()</code>.</li>
  <li>According to <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.1">JLS 15.26.1</a>, it firstly evaluates <code>1 - id</code>. Result is <code>0</code>. It is stored on the thread's stack. We are just about to save that <code>0</code> to static <code>id</code>, but...</li>
  <li>Boom, scheduler chooses the second thread to run.</li>
  <li>So, the second thread enters <code>run()</code>. Static <code>id</code> is still <code>1</code>, so he executes method <code>pick()</code>. <code>P Q</code> is printed.</li>
  <li>Scheduler chooses first thread to run. It takes <code>0</code> from its stack and saves to static <code>id</code>. So, the first thread also executes <code>pick()</code> and prints <code>P Q</code>.</li>
  </ol>
  
  <p>However, in the book it's written that this answer is incorrect:</p>
  
  <blockquote>
    <p>It is incorrect because the line <code>id = 1 - id</code> swaps the value of <code>id</code> between <code>0</code> and <code>1</code>. There is no chance for the same method to be executed twice.</p>
  </blockquote>
  
  <p>I don't agree. I think there is some chance for the scenario I presented above. Such swap is not atomic. Am I wrong?</p>