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;
  }
}

A synchronized modifier on the method is short, but it hides what actually happens. Readers who aren't familiar with the details may not realize that the method locks on this, that the lock spans the whole method body, or that other synchronized methods of the same object share the same lock. Without documentation, this is even harder to see.


/** 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;
    }
  }
}

A synchronized (this) block shows the lock and its scope right in the code: everything inside the braces runs while holding the lock on this, everything outside doesn't. The behavior is exactly the same as before.

Making the lock explicit is the first step to improving it. Now you can see what the lock covers, which allows you to shrink its scope and to replace this with a dedicated lock object, as the next comparisons show.