Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: I can keep the suggestion to synchronize both methods but I have added a line about using volatile too because it is a valid CS...and for the sake of completeness

...

Compliant Solution (synchronization)

This compliant solution guards reads and writes to the flag field with a lock on the instance, i.e., this. This is accomplished by declaring both methods to be synchronized. This solution, via locking, ensures that changes are visible to all the program's threads.declares both the toggle() and getFlag() methods as synchronized.

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

  public synchronized boolean getFlag() { 
    return flag;
  }
}

This guards reads and writes to the flag field with a lock on the instance, that is, this.
This compliant solution ensures that changes are visible to all the threads. It is also permissible to declare flag as volatile to ensure its visibility and while doing so, forgoing to synchronize the getFlag() method. The toggle() method still requires synchronization because it performs a non-atomic operation.

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

...