Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
class Flag {
  private volatile boolean flag = true;
 
  public synchronized void toggle() { 
    flag ^= true; // same as flag = !flag; 
  }

  public boolean getFlag() { 
    return flag;
  }
}

Wiki Markup
The {{toggle()}} method still requires synchronization because it performs a non-atomic operation. However, this advanced technique is brittle in most other scenarios, such as, when a getter method performs operations other than just returning the value of the {{volatile}} field. The cheap read-write lock trick offers performance advantages since the method to read a value {{getFlag()}} is not synchronized. Unless read performance is critical, this method is not recommended. \[[Goetz 06|AA. Java References#Goetz 06]\]

Compliant Solution (java.util.concurrent.atomic.AtomicBoolean)

...