ReentrantLock
A synchronized block is a lock with no name and no options. ReentrantLock is the same lock as an object: it has a lock and an unlock that a program calls itself, a tryLock that answers instead of waiting, and Condition objects for threads that must wait for a state to change.
lock and unlock
The counter from lesson 115 with a lock object instead of a block. The try and finally are not decoration: an exception between the two would leave the lock held for ever, and the finally is the only line that runs in that case:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
public class Locked {
static class Counter {
private final ReentrantLock lock = new ReentrantLock();
private long value;
void increment() {
lock.lock();
try {
value++;
} finally {
lock.unlock();
}
}
boolean tryIncrement() {
if (!lock.tryLock()) {
return false;
}
try {
value++;
return true;
} finally {
lock.unlock();
}
}
long value() {
return value;
}
}
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
List<Thread> workers = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Thread worker = new Thread(() -> {
for (int n = 0; n < 100_000; n++) {
counter.increment();
}
});
workers.add(worker);
worker.start();
}
for (Thread worker : workers) {
worker.join();
}
System.out.println("count: " + counter.value());
System.out.println("exact: " + (counter.value() == 400_000));
counter.lock.lock();
try {
System.out.println("held by main: " + counter.lock.isLocked());
System.out.println("tryLock from the owner: " + counter.tryIncrement() + " (reentrant)");
} finally {
counter.lock.unlock();
}
System.out.println("held after unlock: " + counter.lock.isLocked());
System.out.println("waiting: " + counter.lock.getQueueLength());
}
}
javac -Xlint:all Locked.java
java Locked
count: 400000
exact: true
held by main: true
tryLock from the owner: true (reentrant)
held after unlock: false
waiting: 0
tryLock
tryLock does not wait: it takes the lock if it is free and answers false if it is not. That is the tool of a program that would rather skip the work than queue for it, such as a background job that must not run twice. tryLock(timeout, unit) is the middle ground, and it is the only wait in the API that a program can put a limit on.
The last lines of the program show the reentrant part of the name: the main thread holds the lock, and the same thread takes it again inside tryIncrement without blocking. The count of holds goes to two and the unlock in the method brings it to one. A thread that is not the owner cannot do that, which is why the name is on the class.
Condition and await
A thread that waits for a state to change needs more than a lock: it has to release the lock while it waits, and take it again when it wakes. That is what a Condition does, and the wait is a loop because a wake-up does not promise that the state is the one the thread wanted:
await releases the lock and sleeps until signal or signalAll is called on the same condition, and then it takes the lock again before it returns. The while around it is the rule, not a style: another thread may have taken the state in between.
Two threads, one condition
Two threads alternate through one condition and one integer, and the output is the same on every run because only one of them can be awake when the state allows it:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class PingPong {
static class Turn {
private final ReentrantLock lock = new ReentrantLock();
private final Condition changed = lock.newCondition();
private int state;
void waitFor(int wanted) throws InterruptedException {
lock.lock();
try {
while (state != wanted) {
changed.await();
}
} finally {
lock.unlock();
}
}
void set(int next) {
lock.lock();
try {
state = next;
changed.signalAll();
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
Turn turn = new Turn();
Thread ping = new Thread(() -> {
for (int i = 0; i < 3; i++) {
try {
turn.waitFor(0);
System.out.print("ping ");
turn.set(1);
} catch (InterruptedException e) {
return;
}
}
});
Thread pong = new Thread(() -> {
for (int i = 0; i < 3; i++) {
try {
turn.waitFor(1);
System.out.print("pong ");
turn.set(0);
} catch (InterruptedException e) {
return;
}
}
});
ping.start();
pong.start();
ping.join();
pong.join();
System.out.println();
System.out.println("done");
}
}
javac -Xlint:all PingPong.java
java PingPong
ping pong ping pong ping pong
done
The trailing space is the one the last print leaves, and the empty println ends the line. The order is fixed because the state allows one thread at a time: ping prints only in state 0, pong only in state 1, and each sets the other's state before it lets go.
What a lock allows
Four things that synchronized does not. A tryLock that gives up. A wait with a timeout, through tryLock(time, unit). Several conditions on one lock, so a producer wakes a consumer and not every thread. And a lock that can be inspected: isLocked, getQueueLength and isHeldByCurrentThread are what a diagnostic reads.
The cost is the discipline of the finally. Every path out of the block must unlock, an exception included, and a program that forgets one line stops every thread that needs the lock. A synchronized block cannot forget it, which is why it is still the default and the lock object is for the four cases above.
Exercises
- Take the lock in main, start a worker that calls tryLock, and print what it answers.
- Change signalAll of PingPong to signal and explain why the program can hang.
- Give the counter a method that holds the lock for a hundred increments and run the four threads again.
- Add a second condition to PingPong so that each thread waits on its own.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why is the unlock in a finally block?
Answer
An exception must not leave the lock held
Every path out of the critical section has to release the lock, and finally is the path that always runs.
-
What does
tryLockanswer when the lock is held by another thread?Answer
false, at once
The call is the non-waiting form, and tryLock with a timeout is the bounded wait.
-
Why is the wait of a condition inside a while loop?
Answer
A wake-up does not promise that the state is the one the thread needs
Another thread may consume the state first, so the condition is checked again after every wake-up.
-
What does this program print?
import java.util.concurrent.locks.ReentrantLock; public class Q1 { public static void main(String[] args) { ReentrantLock lock = new ReentrantLock(); System.out.println(lock.isLocked()); lock.lock(); lock.lock(); System.out.println(lock.getHoldCount()); lock.unlock(); lock.unlock(); System.out.println(lock.isLocked()); } }Answer
false / 2 / false
The lock starts free, the same thread holds it twice, and two unlocks free it.
-
What does
getHoldCountreport?Answer
How many times the current thread has taken the lock
It is the reentrant count of this thread, which is two in the quiz program.
-
Why is a lock with several conditions better than one?
Answer
A signal wakes only the threads that wait on that condition
A producer wants to wake a consumer and not every waiter, and a separate condition says so.
-
What does
awaitdo with the lock?Answer
Releases it while waiting and takes it again before returning
The release is what lets the other thread change the state that the wait is about.
-
What does this program print?
import java.util.concurrent.locks.ReentrantLock; public class Q2 { public static void main(String[] args) throws InterruptedException { ReentrantLock lock = new ReentrantLock(); Thread holder = new Thread(() -> { lock.lock(); try { Thread.sleep(200); } catch (InterruptedException e) { return; } finally { lock.unlock(); } }); holder.start(); Thread.sleep(50); System.out.println(lock.tryLock()); holder.join(); System.out.println(lock.tryLock()); lock.unlock(); } }Answer
false / true
The first try comes while the holder sleeps, and the second after the join freed the lock.
-
What is the risk of a lock that is never released?
Answer
Every thread that needs it waits for ever
A held lock is a stop for everyone else, which is why the finally is not optional.
-
When is
synchronizedstill the better choice?Answer
When the plain block is enough, because the compiler cannot forget the unlock
The four features of ReentrantLock are the reason to choose it, and the block is simpler without them.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev