Shared state and data races
What you will learn
A race condition occurs when correctness depends on the interleaving of concurrent actions. Protect an entire business invariant, not merely individual reads and writes. Synchronized blocks and methods use a monitor to make related operations mutually exclusive and visible.
- Reproduce a lost update with a controlled interleaving.
- Protect a stock invariant with a shared monitor.
- Explain circular wait and consistent lock ordering.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Only finite reviewed tasks are started. Latches and barriers coordinate workers with explicit deadlines; their full APIs are covered in Chapter 32. The fixture runner also enforces a process deadline.
Force a lost update with a barrier
import java.time.Duration;import java.util.concurrent.*;public class Main { // Only finite tasks and timed coordination are used in these examples. static void finish(Thread thread) throws InterruptedException { try { if (!thread.join(Duration.ofSeconds(3))) { thread.interrupt(); if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop"); throw new AssertionError("worker timed out"); } } catch (InterruptedException e) { thread.interrupt(); throw e; } } static void meet(CyclicBarrier barrier) { try { barrier.await(3, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError("unexpected cancellation", e); } catch (BrokenBarrierException | TimeoutException e) { throw new AssertionError(e); } } static class Counter { volatile int value; } public static void main(String[] args) throws Exception { CyclicBarrier readTogether = new CyclicBarrier(2); Counter counter = new Counter(); Runnable increment = () -> { int old = counter.value; meet(readTogether); // Both reads finish before either write. counter.value = old + 1; }; Thread a = new Thread(increment); Thread b = new Thread(increment); a.start(); b.start(); try { finish(a); } finally { finish(b); } System.out.println(counter.value); }}Expected output:
1Two increments should total two, but each computes one from the same old value. This is an intentionally broken algorithm with a controlled result, not a recommended counter.
Lost updates and data races
An increment reads a value, calculates a new value, and stores it. A volatile field gives visibility for individual accesses but cannot make the sequence indivisible. The barrier example forces two readers to observe the initial value before either writes. Both then write one, so one logical update disappears. This is a race condition even though the field is volatile. Plain unsynchronized competing writes can also form a JMM data race. A single correct run of a plain counter is not evidence that it is safe.
Monitor ownership and invariants
An instance synchronized method acquires the receiver monitor; a static synchronized method uses its declaring Class object. A synchronized block uses the selected object’s monitor. All paths that read or change the same invariant must follow the same locking protocol. A monitor is reentrant and is released on normal or exceptional exit. Protect check-and-decrement in one critical section. Keep locks private where practical and avoid long blocking operations under them. Do not put a two-party barrier inside a lock that both parties must acquire.
Deadlock prevention
Deadlock is a situation where threads cannot progress because each waits for a resource held by another. Text diagram of a possible bad design: A holds monitor X and waits for Y; B holds Y and waits for X. Both waits form a cycle. Do not execute that design as a lab. A consistent global ordering of distinct locks prevents that particular cycle; the example gives accounts distinct stable IDs. Do not assume it eliminates all application-level deadlocks. Monitor acquisition is not generally interruptible; timed joins detect a failure to finish, not a way to unlock an arbitrary monitor. Advanced explicit locks and diagnostics follow later.
Reserve stock atomically under one monitor
import java.time.Duration;import java.util.concurrent.*;public class Main { // Only finite tasks and timed coordination are used in these examples. static void finish(Thread thread) throws InterruptedException { try { if (!thread.join(Duration.ofSeconds(3))) { thread.interrupt(); if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop"); throw new AssertionError("worker timed out"); } } catch (InterruptedException e) { thread.interrupt(); throw e; } } static void meet(CyclicBarrier barrier) { try { barrier.await(3, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError("unexpected cancellation", e); } catch (BrokenBarrierException | TimeoutException e) { throw new AssertionError(e); } } static final class Inventory { private int stock; Inventory(int stock) { this.stock = stock; } synchronized boolean reserve(int units) { if (units <= 0) throw new IllegalArgumentException("positive units required"); if (stock < units) return false; stock -= units; return true; } synchronized int stock() { return stock; } } public static void main(String[] args) throws Exception { Inventory inventory = new Inventory(5); boolean[] accepted = new boolean[2]; CyclicBarrier start = new CyclicBarrier(2); Thread a = new Thread(() -> { meet(start); accepted[0] = inventory.reserve(4); }); Thread b = new Thread(() -> { meet(start); accepted[1] = inventory.reserve(4); }); a.start(); b.start(); try { finish(a); } finally { finish(b); } System.out.println(accepted[0] ^ accepted[1]); System.out.println(inventory.stock()); }}Expected output:
true1Exactly one reservation can succeed. Which worker wins is unspecified; the XOR and final stock are invariant. Distinct array elements hold each worker’s result and are read after join.
Use consistent lock order for two accounts
import java.time.Duration;import java.util.concurrent.*;public class Main { // Only finite tasks and timed coordination are used in these examples. static void finish(Thread thread) throws InterruptedException { try { if (!thread.join(Duration.ofSeconds(3))) { thread.interrupt(); if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop"); throw new AssertionError("worker timed out"); } } catch (InterruptedException e) { thread.interrupt(); throw e; } } static void meet(CyclicBarrier barrier) { try { barrier.await(3, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError("unexpected cancellation", e); } catch (BrokenBarrierException | TimeoutException e) { throw new AssertionError(e); } } static final class Account { final int id; int balance; Account(int id, int balance) { this.id = id; this.balance = balance; } } static void transfer(Account from, Account to, int units) { if (from == to || from.id == to.id || units <= 0) throw new IllegalArgumentException(); Account first = from.id < to.id ? from : to; Account second = first == from ? to : from; synchronized (first) { synchronized (second) { if (from.balance < units) throw new IllegalArgumentException("insufficient balance"); int credit = Math.addExact(to.balance, units); from.balance -= units; to.balance = credit; } } } public static void main(String[] args) throws Exception { Account left = new Account(1, 10); Account right = new Account(2, 10); CyclicBarrier start = new CyclicBarrier(2); Thread a = new Thread(() -> { meet(start); transfer(left, right, 3); }); Thread b = new Thread(() -> { meet(start); transfer(right, left, 2); }); a.start(); b.start(); try { finish(a); } finally { finish(b); } System.out.println(left.balance + ":" + right.balance); }}Expected output:
9:11Both transfers acquire lower ID then higher ID. Both transfers are affordable in either order; the final total is 20. The example uses two known accounts with distinct IDs, fixed positive amounts and no overflow; a production implementation needs validation.
Common mistakes
Do not assume volatile makes ++ atomic, synchronize on a new object for every call, split a stock check from its update, or acquire the same two monitors in opposite orders. Keep the entire check-and-update under the same monitor.
Practice
Start two workers that each reserve 3 units from an inventory of 6. Verify both succeed and the final balance is zero. Then explain why reserving a seventh unit fails.
Expected output:
true0falseCompare your answer with the manual practice criteria.
Official reading: JLS 17 · Thread · CyclicBarrier. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Shared state and data races — knowledge check
Original concurrency questions. Java 21-compatible scope.
Why can volatile count++ lose updates?
Which monitor does an instance synchronized method acquire?
What should a reservation protect?
How can a consistent lock order help?
What should tests check when either worker may win?