Chapter 1: Protect Your Shared Mutable State ← Use Fair Locks Avoid Active Waiting →

Avoid Locks

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!");
    }

    lock.lock();
    try {
      this.count += amount;
    } finally {
      this.lock.unlock();
    }
  }
}

Locks are a heavy tool for such a simple task. Every call has to acquire and release the lock, threads that can't get it are suspended and woken up again, which costs performance. And as soon as several locks are involved, a wrong order can lead to deadlocks. All this just to add a number.


/** thread safe */
class Counter {

  private final AtomicLong count = new AtomicLong();

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

    this.count.addAndGet(amount);
  }
}

An AtomicLong makes the counter thread-safe without any lock. addAndGet() performs the read, update, and write as a single atomic operation, backed by special instructions of the CPU, such as compare-and-set. Conceptually, it works like this loop, which retries until no other thread has changed the value in between:

long old;
do {
  old = count.get();
} while (!count.compareAndSet(old, old + amount));

The code is shorter, there's no lock to forget to release, and no thread is ever suspended. Atomic variables have been available since Java 5. They work best for a single variable; once several values have to change together, you're back to locks.