Versions Compared

Key

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

...

The second execution order involves the same operations, just that t2 starts and finishes before t1.

Compliant Solution (cheap read-write lock trick)

It is also permissible to declare flag as volatile to ensure its visibility and while doing so, forgoing to synchronize synchronization of the getFlag() method.

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;
  }
}

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.

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

...