title: How to Avoid Data Races - Two Examples
body: <p>I was told that the following code example has a data race condition (assuming multiple threads, of course):</p>
  
  <pre><code>class C { 
   private int x = 0; 
   private int y = 0; 
  
   void f() { 
       x = 1; 
       y = 1; 
   } 
  
   void g() { 
       int a = y; 
       int b = x; 
       assert(b &gt;= a); 
   } 
  } 
  </code></pre>
  
  <p>Yet, I am told that the following "fix" does not have data races:</p>
  
  <pre><code>class C { 
   private int x = 0; 
   private int y = 0; 
  
   void f() { 
       synchronized(this) { x = 1; } 
       synchronized(this) { y = 1; } 
   } 
  
   void g() { 
       int a, b; 
       synchronized(this) { a = y; } 
       synchronized(this) { b = x; } 
       assert(b &gt;= a); 
   } 
  }
  </code></pre>
  
  <p>Understandably, there are other problems with the above examples, but I just want to know why the second code block has no race conditions. How does synchronizing each assignment statement eliminate the data race condition? What is the significance of synchronizing only a single assignment statement at a time?</p>
  
  <p>Just to clarify, data race is defined as such:</p>
  
  <p><code>Data races: Simultaneous read/write or write/write of the same 
  memory location</code></p>