Chapter 1: Protect Your Shared Mutable State

Hide Your Locks


/** thread safe */
class Counter {

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

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

    synchronized (this) {
      this.count += amount;
    }
  }
}
  • as a default, this is the reference of the lock
  • => everybody who has access to that object reference can interfere

/** 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;
    }
  }
}
  • with a private lock object, the lock monitor stays local
  • update documentation!