title: AtomicBoolean vs synchronized block
body: <p>I was trying to cut thread contention in my code by replacing some <code>synchronized</code> blocks with <code>AtomicBoolean</code>.</p>
  
  <p>Here's an example with <code>synchronized</code>:</p>
  
  <pre><code>public void toggleCondition() {
      synchronized (this.mutex) {
          if (this.toggled) {
              return;
          }
  
          this.toggled = true;
          // do other stuff
      }
  }
  </code></pre>
  
  <p>And the alternative with <code>AtomicBoolean</code>:</p>
  
  <pre><code>public void toggleCondition() {
      if (!this.condition.getAndSet(true)) {
          // do other stuff
      }
  }
  </code></pre>
  
  <p>Taking advantage of <code>AtomicBoolean</code>'s CAS property should be way faster than relying on synchronization so I ran a <a href="http://bruno.factor45.org/dumpster/Test.java" rel="noreferrer">little micro-benchmark</a>.</p>
  
  <p>For 10 concurrent threads and 1000000 iterations, <code>AtomicBoolean</code> comes in only slightly faster than <code>synchronized</code> block.</p>
  
  <p>Average time (per thread) spent on toggleCondition() with AtomicBoolean: 0.0338</p>
  
  <p>Average time (per thread) spent on toggleCondition() with synchronized:  0.0357</p>
  
  <p>I know micro-benchmarks are worth what they're worth but shouldn't the difference be higher?</p>