Chapter 1: Protect Your Shared Mutable State

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 undesirable:
    • performance issues
    • deadlocks

/** 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);
  }
}
  • compare-and-set allows lock free
  • available since Java 5
  • requires instruction by the CPU to work
while(true) {
   if(!count.compareAndSet(old, new)) {
      old = count.get();
      new = old + 1;
   }
}