Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Multithreading

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Multithreading

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
Emma holds the printer lock and waits for the scanner. Oliver holds the scanner lock and waits for the printer. Each waits for the other, in a circle, so neither ever continues: a deadlock. Emma Oliver printer lock scanner lock solid: holds, dashed: waits for
Holding one lock and waiting for the other, in a circle: neither can move.

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

IdeaCode
One thread at a timelock.lock(); try { ... } finally { lock.unlock(); }
Deadlocktwo locks taken in opposite order
Fix: lock orderingevery thread takes the locks in the same order
Fix: back offtryLock(50, TimeUnit.MILLISECONDS), then give up

Many shared-data problems are already solved for you; see concurrent collections and virtual threads.

Keep going in Java · 72 of 79

Previous
Java Callable, Future and CompletableFuture
Next post
Java Concurrent Collections and Virtual Threads
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • One lock, one key
  • Each waits for the other
  • Fix 1: the same order, every time
  • Fix 2: wait a while, then give up
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.