Chapter 1: Protect Your Shared Mutable State ← Document for Concurrency Minimize Your Lock Scopes →

Make Locks Explicit


/** thread safe */
class Counter {

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

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

    this.count += amount;
  }
}
  • synchronized in the method may be short, but readers who aren't that familiar with synchronized may get the wrong impression
  • especially if the documentation is missing...

/** thread safe */
class Counter {

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

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

      this.count += amount;
    }
  }
}
  • You should make the scope of the synchronized block explicit