Versions Compared

Key

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

...

Code Block
bgColor#ccccff
final class Flag {
  private boolean flag = true;
  private final ReadWriteLock lock = new ReentrantReadWriteLock();
  private final Lock readLock = lock.readLock();
  private final Lock writeLock = lock.writeLock();
  
  public synchronized void toggle() { 
    writeLock.lock();
    try {
      flag ^= true; // Same as flag = !flag;
    } finally {
      writeLock.unlock();
    }
  }

  public boolean getFlag() { 
    readLock.lock();
    try {
      return flag;
    } finally {
      readLock.unlock();
    }
  }
}

Read-write locks allow a shared state to be accessed by multiple readers or a single writer but never both.

...