Versions Compared

Key

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

...

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

  public Flagboolean getFlag() { // unsafe 
    return flag;
  }
}

...

Code Block
bgColor#FFcccc
class Foo {
  private volatile boolean flag = true;
 
  public void toggle() {  // unsafe
    flag ^= true; 
  }

  public Flagboolean getFlag() { // safe
    return flag;
  }
}

...

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

  public Flagboolean getFlag() { 
    return flag;
  }
}

...

Code Block
bgColor#ccccff
class Foo {
  private AtomicBoolean flag = new AtomicBoolean(true);
 
  public void toggle() { 
    boolean temp;
    do {
      temp = flag.get();
    } while(!flag.compareAndSet(temp, !temp));
  }

  public FlagAtomicBoolean getFlag() { 
    return flag;
  }
}

...