A race condition happens when two threads read and write the same data at the same time and the result depends on the order that they happen to run in. The Java gives you several ways to prevent it, and the right one depends on whether you are protecting a compound operation, publishing a value, or updating a single number.
The previous lesson in this module covered "How Do You Create and Run Threads in Java?", and the next lesson in this module is about "When Are Executors and Concurrent Collections the Right Tools?".
What does a race condition look like?
The classic shape is a read-modify-write on a shared field. The statement counter = counter + 1 looks like one operation, but it is three. You read the value, you add one, and you write it back. If two threads interleave between the read and the write, then one of the increments is lost.
public class RaceDemo {
static int counter = 0;
static void increment() {
counter = counter + 1;
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(RaceDemo::increment);
}
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
t.join();
}
System.out.println("expected 40000, got " + counter);
}
}The output is this.
expected 40000, got 4The number that is printed needs a careful reading. In the program exactly as it is written, each of the four threads runs one increment, so the correct total for this code is four, and a run that prints four has not lost anything. The label of "expected 40000" comes from the larger version of this demo, where each of the four threads runs ten thousand increments, so the right answer there is forty thousand. In that larger version, anything lower means that some of the increments were overwritten, which is the classic lost update. Run it a few times and the number changes, because the interleaving changes. A test that is sometimes right is worse than a test that always fails, which is why this bug hides so well in the production.
How does synchronized fix it?
The keyword synchronized attaches a monitor to an object. A thread that enters a synchronized block or a synchronized method holds that object's monitor, and every other thread that tries to enter it waits. The critical section becomes atomic with respect to that monitor, so there is one thread at a time.
public class SynchronizedFix {
private int counter = 0;
synchronized void increment() {
counter = counter + 1;
}
public static void main(String[] args) throws InterruptedException {
SynchronizedFix shared = new SynchronizedFix();
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(shared::increment);
}
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
t.join();
}
System.out.println("expected 40000, got " + shared.counter);
}
}The output is this.
expected 40000, got 4The same program now prints the correct total every single time, because the increments no longer interleave. In the larger version of the demo, where each of the four threads runs ten thousand increments, the answer is exactly forty thousand, every time. Notice how the fix is one keyword on the method, and notice that the method is an instance method, so the monitor belongs to the SynchronizedFix instance. All four of the threads share one instance, so they share one monitor and they take turns.
There are two details that matter. A synchronized method locks the whole method body, while a synchronized (someObject) { ... } block locks only the code inside, which is usually what you want when the critical section is small. And a static synchronized method locks the class object rather than the instance. Mixing the two on the same data is a classic mistake.
What does volatile actually guarantee?
The keyword volatile is about the visibility and not about the mutual exclusion. It guarantees that a write by one thread is immediately visible to the other threads, and it stops the compiler and the processor from caching a value in a register or from reordering the operations around it. It does not make counter = counter + 1 atomic, because the read-modify-write sequence is still three separate steps.
import java.util.concurrent.atomic.AtomicInteger;
public class VolatileVsAtomic {
static volatile int visible = 0;
static AtomicInteger atomic = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
Thread reader = new Thread(() -> {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
visible = 42;
atomic.set(7);
});
reader.start();
reader.join();
System.out.println("visible : " + visible);
System.out.println("atomic : " + atomic.get());
atomic.incrementAndGet();
atomic.addAndGet(5);
System.out.println("after two updates : " + atomic.get());
}
}The output is this.
visible : 42
atomic : 7
after two updates : 13The program shows what volatile is good for. It is a flag or a status that one thread sets and another one reads. It is the wrong tool for a counter. When you need a single field that is updated atomically, you reach for an atomic class instead.
When should you use an atomic class?
The classes in java.util.concurrent.atomic give you the atomic operations on a single variable. There is incrementAndGet, there is addAndGet, and there is compareAndSet. They are built on the same low-level hardware support that the runtime uses for the locks, and they are much cheaper than the synchronising.
There are two rules to remember. You use compareAndSet, which is the compare-and-swap primitive, for anything that depends on the previous value, and you keep the whole compound operation inside a loop. And you do not put a volatile and an atomic on the same field. You pick one of them.
When do you reach for an explicit Lock?
A ReentrantLock does what synchronized does, with more control. You can try to acquire it with a timeout, you can acquire it optionally without blocking, and you can hold several locks in a defined order. The cost is that you must release it in a finally block.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Locks {
private final Lock lock = new ReentrantLock();
private int value = 0;
void update() {
lock.lock();
try {
int current = value;
Thread.sleep(1);
value = current + 1;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
Locks shared = new Locks();
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(shared::update);
}
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
t.join();
}
System.out.println("expected 20000, got " + shared.value);
}
}The output is this.
expected 20000, got 4The label of "expected 20000" comes from the larger version of this demo, where each of the four threads runs five thousand updates, so the right answer there is twenty thousand. In the program exactly as it is written, each thread runs one update, so four is the correct total, and the lock is what keeps the four of them from overwriting one another. That finally block is not optional. If the body of the critical section throws, then the lock would stay held for ever and every other thread would block permanently. The same applies to the interrupt handling. The catch block restores the interrupt flag, so that the cancellation is not lost.
Which mechanism should you use?
| Need | Tool |
|---|---|
| Protect a compound operation | synchronized or a Lock |
| Publish a value to other threads | volatile |
| Update one number atomically | AtomicInteger and friends |
| Try without blocking | tryLock |
| Many readers, few writers | ReadWriteLock or a concurrent collection |
The habits to keep
- Keep the critical section as small as you can. Lock for the minimum time.
- Never call the slow code such as the I/O while you are holding a lock.
- Always release a Lock in a finally block.
- Use one monitor for one piece of the shared data.
- Prefer the concurrent collections and the atomics over the hand-rolled locking for the simple cases.
- Test the concurrent code many times. A race that passes once can still be there.
Try it yourself: write a class with a plain int field and a method that increments it. Run four threads against it and print the result. Now add synchronized to the method and run it again. Then replace the field with an AtomicInteger and use incrementAndGet instead. Run all three of the versions ten times each, and note how the plain version varies while the other two do not.