Chapter 1: Protect Your Shared Mutable State Document for Concurrency →

Protect Your Shared Memory

class Counter {

  private long count;

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

    this.count += amount;
  }
}

Welcome to this series of comparisons about strategies for reading and writing shared memory from multiple threads.

Look at this Counter class. It has a private variable count, which can only be increased with the increment() method. If the amount is at least 1, the method adds it to the previous value of count. This is perfectly fine Java code in a single-threaded world.

Issues arise as soon as two or more threads call increment() at the same time. Imagine two threads calling increment(1) 100 times each on the same counter, starting at 0. We would expect 200, but count can end up with basically any value up to 200. How can this happen?

The problem hides behind this.count += amount;. Although it's a single line, the += operator expands to three steps:

var tmp = count;    // read
tmp = tmp + amount; // update
count = tmp;        // write

First, the thread reads the current value of count into a temporary variable. Second, it updates that temporary value. Third, it writes the result back into count. Such a sequence is called a critical section: it is only correct if no other thread interferes while it runs. With two threads, the steps can interleave like this:

var tmp1 = count;     // T1 read
tmp1 = tmp1 + amount; // T1 update
var tmp2 = count;     // T2 read
tmp2 = tmp2 + amount; // T2 update
count = tmp1;         // T1 write
count = tmp2;         // T2 write

T1 reads and updates, but before it can write, the scheduler lets T2 run. T2 reads the same old value and updates it. Then T1 writes its result, and T2 overwrites it with its own. The increment of T1 is gone: a lost update. The Java Memory Model allows this, since the program order only holds within a single thread: "compilers are allowed to reorder the instructions in either thread, when this does not affect the execution of that thread in isolation". And because count is a long, it gets even worse: the JVM may write the two 32-bit halves of a 64-bit value separately, so another thread could even read a value that was never written.

Would you have thought that such innocent-looking code can lead to incorrect programs? On the right, we protect the shared memory so that only one thread at a time can be in the critical section.

class Counter {

  private long count;

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

    this.count += amount;
  }
}

The synchronized keyword on the method ensures that only one thread at a time can execute increment() on the same Counter object. A thread that wants to enter has to acquire the object's lock first. If another thread holds it, the thread waits until the lock is released.

So the read, update, and write of count now run as one atomic unit, and lost updates can no longer happen: two threads calling increment(1) 100 times each always end at 200. synchronized also guarantees visibility, so a thread entering the method sees all writes made by the previous holder of the lock.

This one keyword makes the code correct. The following comparisons make it clearer, faster, and safer to use.