Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
kvi5hnuCode Sprout team member10 min readOn this page
In most real multithreaded programs, several threads need to share data. What happens when two threads update the same object at the same time? Depending on exactly how their steps interleave, the object can end up corrupted. This is a race condition, and it is the central danger of concurrent programming. Race conditions are hard to reproduce: a buggy program may run correctly a thousand times and then fail on a customer's busier machine. This article shows exactly how races happen and introduces the first tool for preventing them, ReentrantLock.
A bank that loses money
Go back to the simulated bank from article 92, but now let many threads transfer between randomly chosen accounts. Each of 100 threads keeps moving money out of "its" account to a random other account:
public void transfer(int from, int to, double amount) { // CAUTION: unsafe with several threads
if (accounts[from] < amount) return;
accounts[from] -= amount;
accounts[to] += amount;
}
Money only moves between accounts, so the total should never change. Run it with enough threads, though, and print the total after each transfer, and you'll see it stay at the expected value for a while, then drift: a few dollars vanish here, a few appear there. Sometimes it goes wrong within milliseconds, sometimes only after hours. Few things are worse in a programmer's life than an error that only shows up now and then.
The race condition explained
The problem is that a statement like
accounts[to] += amount;
is not atomic. It takes several machine steps:
- Load
accounts[to]into a register. - Add
amount. - Store the result back into
accounts[to].
A thread can be preempted between any two of these steps. Suppose thread A loads the balance of 1,000 and is then paused. Thread B loads the same 1,000, adds its 500, and stores 1,500. Thread A wakes up, adds its 200 to the stale 1,000 it loaded earlier, and stores 1,200. B's deposit is gone.

You can see the individual steps in the bytecode. javap -c -v Bank shows that accounts[to] += amount compiles to a sequence of instructions (getfield, daload, dadd, dastore and more), and a thread can lose the processor after any of them. On modern multicore hardware, two threads don't even need to be preempted. They can run these steps simultaneously on different cores. Even a lowly counter++ is a race: the demo has four threads increment a shared counter a million times each, and the unsynchronized total usually comes up short.
The core issue is that the transfer method can be interrupted halfway through. If each transfer were guaranteed to run to completion before another thread could touch the same accounts, the data would never be corrupted. That guarantee is what locks provide.
Lock objects
Java has two mechanisms for protecting a block of code from concurrent access: the synchronized keyword, and the explicit lock classes in java.util.concurrent.locks. synchronized is shorthand for a lock plus a condition, so it is easier to understand once you have seen explicit locks and conditions on their own. This article covers locks, and the next covers conditions and synchronized.
Here's the basic pattern for protecting code with a ReentrantLock:
myLock.lock(); // a ReentrantLock object
try {
critical section
} finally {
myLock.unlock(); // make sure the lock is released
}
Only one thread at a time can be inside the critical section. The first thread to call lock() acquires the lock. Every other thread that calls lock() is deactivated, in the WAITING state, until the owner calls unlock(). Then one of the waiting threads gets the lock and proceeds.
You can't use try-with-resources here, because Lock isn't AutoCloseable. Some developers proposed it, but the Java designers wanted explicit locking to stay visible in the code.
Protecting the bank looks like this:
public class Bank {
private final Lock bankLock = new ReentrantLock();
public void transfer(int from, int to, long amount) {
bankLock.lock();
try {
if (accounts[from] < amount) return;
accounts[from] -= amount;
accounts[to] += amount;
} finally {
bankLock.unlock();
}
}
}
Now, if one thread is preempted halfway through a transfer, a second thread calling transfer blocks at lock() until the first one finishes. You can run the simulation forever and the total never changes.
Each Bank object has its own lock. Two threads working on the same bank are serialized. Two threads working on different banks use different locks and don't block each other, which is exactly right, because they can't interfere. Note too that getTotalBalance must lock as well. A reader that skips the lock can observe a transfer halfway through, with money already gone from one account and not yet in the other.
Reentrancy and the hold count
The lock is called reentrant because a thread that already owns it can acquire it again. The lock keeps a hold count: each lock() increments it, and each unlock() decrements it. The lock is released only when the count reaches zero. So code protected by a lock can call another method that uses the same lock. If transfer calls getTotalBalance, which also locks bankLock, the hold count goes to 2, back to 1 when getTotalBalance returns, and to 0 when transfer finishes. Without reentrancy, a thread calling a locked method from another locked method would deadlock on itself.
As a rule, put a lock around every block that updates or reads shared state, so that each operation runs to completion before another thread can see the object.
Other ReentrantLock features
tryLock()acquires the lock only if it's free right now, and returnsfalseotherwise.tryLock(time, unit)waits up to the given time. Both are useful for avoiding deadlocks or doing something else when a resource is busy (article 99).lockInterruptibly()acquires the lock but gives up withInterruptedExceptionif the thread is interrupted while waiting. Plainlock()ignores interrupts.- Diagnostics:
isLocked(),isHeldByCurrentThread(),getHoldCount(),hasQueuedThreads()andgetQueueLength()are handy in assertions and tests.
Fair locks
new ReentrantLock(true) creates a fair lock, which favours the thread that has waited longest. That sounds good, but fairness costs a lot of throughput, because the lock can't hand itself to whichever thread happens to be running. Even a fair lock can't make the thread scheduler fair, and the untimed tryLock() barges in regardless of fairness. Use fair locks only when you have a measured reason to.
A complete example
The demo first replays the lost update by hand, which is deterministic. Then it runs four threads incrementing a counter with and without a lock, and 100 transfer tasks against a locked bank with balances in cents, so the arithmetic is exact. It also explores reentrancy, unlocking after an exception, the error you get from unlocking a lock you don't hold, and tryLock on a fair lock.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class Solution {
// a bank whose transfer method is protected by a ReentrantLock
static class Bank {
private final long[] accounts; // balances in cents: exact arithmetic
private final Lock bankLock = new ReentrantLock();
Bank(int n, long initialBalance) {
accounts = new long[n];
Arrays.fill(accounts, initialBalance);
}
void transfer(int from, int to, long amount) {
bankLock.lock();
try {
if (accounts[from] < amount) return; // insufficient funds: skip
accounts[from] -= amount;
accounts[to] += amount;
} finally {
bankLock.unlock(); // always, even on exceptions
}
}
long total() {
bankLock.lock();
try {
long sum = 0;
for (long a : accounts) sum += a;
return sum;
} finally {
bankLock.unlock();
}
}
}
static int counter; // shared, unprotected
public static void main(String[] args) throws Exception {
// 1. a lost update, replayed step by step
int balance = 1000;
int regA = balance; // thread A: load
int regB = balance; // thread B: load (A was preempted)
regB += 500; // thread B: add
balance = regB; // thread B: store -> 1500
regA += 200; // thread A resumes: add
balance = regA; // thread A: store -> 1200, B's deposit is gone
System.out.println("deposits of 200 and 500 to 1000 interleaved badly: balance " + balance + " instead of 1700");
// 2. the same thing with real threads: counter++ is not atomic
int threads = 4, increments = 1_000_000;
try (ExecutorService pool = Executors.newFixedThreadPool(threads)) {
for (int t = 0; t < threads; t++) pool.submit(() -> { for (int i = 0; i < increments; i++) counter++; });
}
System.out.println("unsynchronized counter: never more than " + threads * increments + ": "
+ (counter <= threads * increments) + " (lost updates are likely, but not guaranteed)");
// 3. with a lock, no update is lost
counter = 0;
var lock = new ReentrantLock();
try (ExecutorService pool = Executors.newFixedThreadPool(threads)) {
for (int t = 0; t < threads; t++)
pool.submit(() -> {
for (int i = 0; i < increments; i++) {
lock.lock();
try { counter++; } finally { lock.unlock(); }
}
});
}
System.out.println("locked counter: " + counter);
// 4. 100 tasks on 8 threads transferring money: the lock preserves the total
var bank = new Bank(100, 100_000);
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
for (int from = 0; from < 100; from++) {
int f = from;
pool.submit(() -> {
var random = new Random(f);
for (int i = 0; i < 20_000; i++) {
int to = random.nextInt(100);
long amount = random.nextInt(50_000);
bank.transfer(f, to, amount);
}
});
}
}
System.out.println("locked bank total " + bank.total() + " (expected 10000000)");
// 5. reentrancy and the hold count
var reentrant = new ReentrantLock();
reentrant.lock();
reentrant.lock(); // same thread again: OK
System.out.println("hold count " + reentrant.getHoldCount() + ", held by me " + reentrant.isHeldByCurrentThread());
reentrant.unlock();
System.out.println("after one unlock: hold count " + reentrant.getHoldCount() + ", locked " + reentrant.isLocked());
reentrant.unlock();
System.out.println("after second unlock: locked " + reentrant.isLocked());
// 6. an exception inside the critical section still releases the lock
try {
reentrant.lock();
try {
throw new IllegalStateException("failure halfway through");
} finally {
reentrant.unlock();
}
} catch (IllegalStateException e) {
System.out.println("exception in critical section; lock still held? " + reentrant.isLocked());
}
// 7. unlocking a lock you don't own
try {
new ReentrantLock().unlock();
} catch (IllegalMonitorStateException e) {
System.out.println("unlock without lock: IllegalMonitorStateException");
}
// 8. tryLock when another thread holds the lock
var busy = new ReentrantLock(true); // a fair lock
var holding = new CountDownLatch(1);
var release = new CountDownLatch(1);
Thread holder = Thread.ofPlatform().start(() -> {
busy.lock();
try {
holding.countDown();
release.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
busy.unlock();
}
});
holding.await();
System.out.println("fair " + busy.isFair() + ", tryLock while held elsewhere: " + busy.tryLock()
+ ", queued threads " + busy.hasQueuedThreads());
release.countDown();
holder.join();
boolean got = busy.tryLock(1, TimeUnit.SECONDS);
System.out.println("tryLock after release: " + got);
if (got) busy.unlock();
}
}
deposits of 200 and 500 to 1000 interleaved badly: balance 1200 instead of 1700
unsynchronized counter: never more than 4000000: true (lost updates are likely, but not guaranteed)
locked counter: 4000000
locked bank total 10000000 (expected 10000000)
hold count 2, held by me true
after one unlock: hold count 1, locked true
after second unlock: locked false
exception in critical section; lock still held? false
unlock without lock: IllegalMonitorStateException
fair true, tryLock while held elsewhere: false, queued threads false
tryLock after release: true
The unsynchronized counter prints only a safe comparison, because its actual value changes from run to run. That randomness is the whole problem. With the lock, the counter and the bank total are exact every time.
Common questions
Why isn't count++ thread-safe?
It reads the field, adds 1, and writes the result back in three separate steps. Two threads can read the same old value, and one increment is lost. Use a lock, synchronized, or an AtomicInteger.
Why must lock() go before the try?
If lock() fails with an exception inside the try, the finally block would call unlock() on a lock the thread doesn't hold, which throws IllegalMonitorStateException and hides the original error. Calling lock() first means the finally only runs once the lock is actually held.
Do I need a lock just to read shared data?
Yes, unless the data is immutable or the field is volatile and the read is a single value. A reader without the lock can see an update halfway through, or a stale value that another thread changed long ago.
Should I use fair locks? Usually not. Fair locks are much slower, and they still don't make thread scheduling fair. Use them only if measurements show that some threads are starved.
ReentrantLock or synchronized?
Use synchronized for simple critical sections: it's shorter, and you can't forget to unlock. Use ReentrantLock when you need tryLock, a timeout, interruptible locking, several conditions or fairness.
API reference
java.util.concurrent.locks.Lock
| Method | Description |
|---|---|
void lock() | acquires the lock, waiting if another thread owns it |
void unlock() | releases the lock; IllegalMonitorStateException if not the owner |
boolean tryLock() | acquires the lock if it's free right now |
boolean tryLock(long time, TimeUnit unit) | waits up to the given time; interruptible |
void lockInterruptibly() | like lock, but throws InterruptedException if interrupted while waiting |
Condition newCondition() | a condition object tied to this lock (article 98) |
java.util.concurrent.locks.ReentrantLock
| Method | Description |
|---|---|
ReentrantLock() | a non-fair reentrant lock |
ReentrantLock(boolean fair) | true favours the longest-waiting thread (slower) |
int getHoldCount(), boolean isHeldByCurrentThread(), boolean isLocked() | ownership diagnostics |
boolean isFair(), boolean hasQueuedThreads(), int getQueueLength() | fairness and queue diagnostics |
Summary
- A race condition happens when threads interleave the steps of a non-atomic operation on shared data.
x += yandcounter++are load-add-store sequences. - Check-then-act and read-modify-write sequences must be protected as a whole, and so must reads of state that other threads modify.
ReentrantLockmakes a block a critical section. Always writelock(); try { … } finally { unlock(); }.- Locks are per object. Threads using different objects don't block each other.
- Reentrancy lets the owner re-acquire the lock, and a hold count tracks how many times.
tryLockandlockInterruptiblyavoid indefinite waiting. Fair locks are slow, so use them only when necessary.
Practice Questions
Why can two threads each executing count++ once leave count increased by only 1?
count++ is load, add and store. Both threads can load the same old value, each adds 1, and both store the same new value, so one increment is lost.
What is wrong with this code? lock.lock(); doWork(); lock.unlock();
If doWork throws, unlock never runs and the lock stays held forever, blocking every other thread that needs it. Put unlock() in a finally block.
A method locks bankLock and then calls another method that also locks bankLock. Does the thread deadlock?
No. ReentrantLock is reentrant: the owner can lock it again, and the hold count goes to 2. The lock is released only after a matching number of unlock calls.
Two threads call transfer on two different Bank objects. Do they block each other?
No. Each Bank has its own lock, so they hold different locks and proceed independently.
Why isn't fair locking the default?
Fair locks hand the lock to the longest-waiting thread instead of the one that happens to be running, which causes far more context switches and much lower throughput. Most programs don't need strict fairness.
Previous: Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Next: Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Related reading
- Java Callable, Future and ExecutorService: Thread Pools and Task Results
- Java Virtual Threads, Interrupts and Daemon Threads: Thread Properties Explained
- Java Thread States: New, Runnable, Blocked, Waiting and Terminated
- Java Threads: Creating and Running Threads with Runnable and Thread
- Java Object Construction: Overloading, Default Fields, this(), and Initialization Blocks

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Java Callable, Future and ExecutorService: Thread Pools and Task Results
Run tasks that return results with Callable and Future, then let an ExecutorService manage threads: fixed, cached and single-thread pools, virtual-thread-per-task executors, get with timeouts, cancellation, Future.state and resultNow, closing executors, and throttling with semaphores.
Discussion
Sign in to ask a question or share what you learned.