Java Locks, Deadlock and tryLock
A ReentrantLock lets Emma and Oliver deposit 10,000 each for a balance of exactly 20,000. Then Emma holds the printer and wants the scanner while Oliver holds the scanner and wants the printer: a deadlock. Taking locks in the same order fixes it, and so does tryLock with a timeout.
What you will learn
- Guard shared data with a ReentrantLock and always unlock in finally
- Compare a ReentrantLock with synchronized
- Explain how two threads taking two locks in opposite order deadlock
- Avoid deadlock with a fixed lock order or with tryLock and a timeout
Before you start
- Java race conditions and synchronized
- Java exception handling: try, catch and finally
A lock lets one thread at a time into a piece of code. This lesson shows a ReentrantLock, how two threads can wait for each other forever, and two ways out of that. The sleeps in these programs set the order of events; real timings vary run to run.
One lock, one key
package org.studyeasy.s06l08;
import java.util.concurrent.locks.ReentrantLock;
public class Ex01_ReentrantLock {
static final ReentrantLock lock = new ReentrantLock();
static int balance = 0;
static void deposit(int amount) {
lock.lock(); // busy? wait here until it is free
try {
balance += amount;
} finally {
lock.unlock(); // finally: released even after an error
}
}
public static void main(String[] args) throws InterruptedException {
Runnable pay = () -> {
for (int i = 0; i < 10000; i++) deposit(1);
};
Thread emma = new Thread(pay);
Thread oliver = new Thread(pay);
emma.start();
oliver.start();
emma.join();
oliver.join();
System.out.println("Balance: " + balance);
}
}
Balance: 20000
Think of the lock as having exactly one key. lock() takes it, or waits if another thread has it; only the key holder may change the balance. unlock() gives it back, and it goes in a finally block so the key is returned even after an error. Delete unlock() and Emma never lets go, so Oliver waits forever.
With synchronized, Java locks and unlocks for you. With a ReentrantLock you do it yourself, and in return you get extras such as tryLock, which can give up after waiting a while.
Each waits for the other
A Device (a printer or a scanner) has its own ReentrantLock. Copying a page needs both:
static void copy(Device first, Device second) {
String me = Thread.currentThread().getName();
first.lock.lock();
try {
System.out.println(me + " has the " + first.name
+ ", wants the " + second.name);
Device.pause(100); // time for the other to lock its first
second.lock.lock(); // held by the other? wait here
try {
System.out.println(me + " copies a page");
} finally {
second.lock.unlock();
}
} finally {
first.lock.unlock();
}
}
// Emma: printer first. Oliver: scanner first
Thread emma = new Thread(() -> copy(printer, scanner), "Emma");
Thread oliver = new Thread(() -> copy(scanner, printer), "Oliver");
Emma has the printer, wants the scanner
Oliver has the scanner, wants the printer
Then nothing. There's no "Done" line; the program hangs (stop it with the red square in IntelliJ or Ctrl+C). Emma locks the printer, Oliver locks the scanner, then each waits for the device the other holds. That circle of waiting is a deadlock.
Fix 1: the same order, every time
// both take the printer first, then the scanner
Thread emma = new Thread(() -> copy(printer, scanner), "Emma");
Thread oliver = new Thread(() -> copy(printer, scanner), "Oliver");
Emma has the printer, wants the scanner
Emma copies a page
Oliver has the printer, wants the scanner
Oliver copies a page
Done
The only change: both threads take the printer first. Emma gets it, and Oliver waits for the printer while holding nothing, so the scanner is free for Emma. She copies, lets go, and Oliver goes next. With one fixed order, a circle can't form.
Fix 2: wait a while, then give up
if (second.lock.tryLock(patience, TimeUnit.MILLISECONDS)) {
try {
System.out.println(me + " copies a page");
} finally {
second.lock.unlock();
}
} else {
System.out.println(me + " gave up on the " + second.name);
}
Thread emma = new Thread(() -> copy(printer, scanner, 50), "Emma");
Thread oliver = new Thread(() -> copy(scanner, printer, 1000), "Oliver");
Emma has the printer, wants the scanner
Oliver has the scanner, wants the printer
Emma gave up on the scanner
Oliver copies a page
Done
Back to the opposite order, but tryLock waits only for a while: 50 ms for Emma, 1000 for Oliver. Emma's wait ends first, so tryLock returns false, she gives up and her finally releases the printer. Oliver, still waiting, gets it and copies. (tryLock can be interrupted, so the full method also catches InterruptedException.)
Recap
| Idea | Code |
|---|---|
| One thread at a time | lock.lock(); try { ... } finally { lock.unlock(); } |
| Deadlock | two locks taken in opposite order |
| Fix: lock ordering | every thread takes the locks in the same order |
| Fix: back off | tryLock(50, TimeUnit.MILLISECONDS), then give up |
Many shared-data problems are already solved for you; see concurrent collections and virtual threads.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Concurrency: Processes, Threads and the Main Thread in Java
Every Java program runs as a process and starts on one thread, main. One cook takes 15 seconds for soup and salad; a second thread, Jack, brings it to 10. Then two threads add to one counter a million times each and count less than 2,000,000.
Creating Threads in Java: Thread, Runnable and Lambdas
Three ways to give a thread its job: an InvoiceMailer that extends Thread, a ReportTask record that implements Runnable, and a lambda. worker.run() prints main, worker.start() prints backup-worker, and two cashiers, Jack and Liam, scan items in an order that changes every run.
Java Thread Lifecycle: sleep, join and interrupt
A courier thread walks from NEW through RUNNABLE and TIMED_WAITING to TERMINATED while main WAITs at join. An interrupt wakes a sleeping download on report-3: one version retries it, the other returns. And a daemon status thread dies when the last user thread ends.
Java Race Conditions and synchronized
Two cashiers each sell a million tickets on one counter and the total comes out short, a different number every run, because sold++ is read, add, write. A synchronized method or a synchronized block on one shared lock gives exactly 2,000,000; a new Object() lock protects nothing.
