Chapter 1: Protect Your Shared Mutable State

Use Fair Locks


/** thread safe */
class Counter {

  /** guarded by 'lock' */
  private long count;

  private final Object lock = new Object();

  void increment(long amount) {
    if (amount < 1) {
      throw new IllegalArgumentException("Only increments!");
    }

    synchronized (this.lock) {
      this.count += amount;
    }
  }
}
  • unfair, random

/** thread safe */
class Counter {

  /** guarded by 'lock' */
  private long count;

  private final ReentrantLock lock = new ReentrantLock(true);

  void increment(long amount) {
    if (amount < 1) {
      throw new IllegalArgumentException("Only increments!");
    }

    this.lock.lock();
    try {
      this.count += amount;
    } finally {
      this.lock.unlock();
    }
  }
}
  • same behavior as synchronized
  • but also fair (see true parameter in the constructor), real fcfs
  • this comes at a slight cost
  • close your resources with finally (link to other comparison)