Java Lock vs synchronized: Timeout, Interrupt & Fair Locking Explained

This article compares Java's synchronized keyword with the Lock interface (ReentrantLock), demonstrating how Lock provides finer-grained control through timeout acquisition (tryLock), interruptible locking (lockInterruptibly), fair/non-fair policies, and manual unlock in finally blocks, with code examples for each scenario.

samdeepthink
samdeepthink
samdeepthink
Java Lock vs synchronized: Timeout, Interrupt & Fair Locking Explained

Pain Points with synchronized

In high-concurrency scenarios, synchronized has two critical limitations: it cannot acquire a lock with a timeout (it blocks indefinitely), and it cannot respond to thread interruption. If a thread waits for a lock and the business context changes (e.g., user cancels a request), the thread remains blocked forever.

Lock Interface: Flexible Control

The Lock interface (typically implemented by ReentrantLock) moves locking control to the API level, enabling fine-grained concurrency management.

Basic Lock/Unlock with try-finally

Unlike synchronized which releases automatically, Lock requires manual release in a finally block to prevent deadlocks.

Lock lock = new ReentrantLock();
lock.lock(); // blocking acquire
try {
    // operate on shared resource
} finally {
    lock.unlock(); // mandatory release
}

Non-blocking & Timeout Acquisition (tryLock)

tryLock()

attempts immediate acquisition; tryLock(timeout, unit) waits up to the specified duration. This avoids indefinite blocking and enables fallback logic.

// try to acquire, wait up to 5 seconds
if (lock.tryLock(5, TimeUnit.SECONDS)) {
    try {
        // got the lock, execute core business
    } finally {
        lock.unlock();
    }
} else {
    // timed out after 5 seconds, execute fallback or fail fast
    System.out.println("System busy, please try later");
}

Interruptible Lock Acquisition (lockInterruptibly)

lockInterruptibly()

allows a waiting thread to be interrupted by another thread. When interrupted, it throws InterruptedException, enabling graceful termination.

Complete example demonstrating the pattern:

public static void main(String[] args) throws InterruptedException {
    Lock lock = new ReentrantLock();

    // 1. Main thread acquires lock first
    lock.lock();
    System.out.println("Main thread: I hold the lock and won't release yet.");

    // 2. Worker thread attempts interruptible lock acquisition
    Thread workerThreadA = new Thread(() -> {
        System.out.println("Worker: attempting to acquire lock, can wait but accept interruption...");
        try {
            lock.lockInterruptibly(); // blocks here because main holds lock
            try {
                System.out.println("Worker: acquired lock, starting work!");
            } finally {
                lock.unlock();
            }
        } catch (InterruptedException e) {
            // 4. Worker receives interrupt signal while waiting
            System.out.println("Worker: interrupted while waiting, exiting!");
            Thread.currentThread().interrupt(); // restore interrupt flag
        }
    });

    workerThreadA.start();

    // Main thread simulates work for 2 seconds while worker blocks
    Thread.sleep(2000);

    // 3. Business change: main thread interrupts worker
    System.out.println("Main thread: business changed, interrupting worker!");
    workerThreadA.interrupt(); // key action: external thread calls interrupt()

    // Main thread releases its lock
    lock.unlock();
}

Key points:

Who calls interrupt()? An external thread (here the main thread), not the waiting thread itself. The waiting thread is the executor; the external thread is the controller.

Real-world scenario: A user clicks "Generate Report", spawning a worker thread that waits for a lock. If the user clicks "Cancel" after 2 seconds, the request-handling thread calls interrupt() on the worker. With synchronized, the worker would remain blocked indefinitely; with lockInterruptibly(), it throws InterruptedException and exits cleanly.

Fair vs Non-fair Locks

synchronized

is always non-fair (threads compete arbitrarily). ReentrantLock supports both: pass true to the constructor for a fair lock (FIFO queue), false (default) for non-fair. Fair locks suit strict ordering requirements; non-fair locks generally provide higher throughput.

// true = fair lock, threads acquire in arrival order
Lock fairLock = new ReentrantLock(true);

Comparison Summary

The following dimensions highlight the differences:

Implementation: synchronized is a JVM keyword (monitorenter/monitorexit bytecodes); Lock is a JDK-level interface/class.

Lock Release: synchronized releases automatically; Lock requires manual unlock() in finally.

Timeout Acquisition: synchronized does not support; Lock provides tryLock(timeout, unit).

Interrupt Response: synchronized ignores interrupts; Lock offers lockInterruptibly().

Non-blocking Attempt: synchronized cannot; Lock provides tryLock().

Fairness: synchronized only non-fair; Lock supports both via constructor.

Reentrancy: Both are reentrant.

When to Choose Which

For simple mutual exclusion, prefer synchronized for its simplicity and automatic release:

synchronized (lock) {
    // modify shared data
}

Choose Lock when you need timeout acquisition, interruptible waiting, non-blocking attempts, fair locking, or Condition variables.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaconcurrencyLocktimeoutReentrantLockSynchronizedFair LockThread Interrupt
samdeepthink
Written by

samdeepthink

Knowledge Planet: Old Dock's Tech Chronicles Zhihu: SamDeepThinking A technical manager who still codes heavily on the front line. From junior developer to tech lead, then tech manager, now leading the whole front‑ and back‑end development team—leveling up along the way. I have some insights on programming, career development, and tech management.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.