ReentrantLock lockInterruptibly Cancels Waiting

lockInterruptibly lets a blocked waiter be cancelled by interrupt, unlike lock(), so stuck lock waits cannot pin threads forever.

JavaResilience

Code

snippet
import java.util.concurrent.locks.ReentrantLock;

public class InterruptibleLock {

    private static final ReentrantLock gate = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread holder = Thread.ofPlatform().name("holder").start(() -> {
            gate.lock();
            try {
                Thread.sleep(300); // 长临界区:等待者被堵在队列里
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                gate.unlock();
            }
        });

        Thread.sleep(50); // holder 先拿到锁,waiter 进队等待
        Thread waiter = Thread.ofPlatform().name("waiter").start(() -> {
            try {
                // lockInterruptibly cancels waiting when interrupted
                gate.lockInterruptibly();
                try {
                    System.out.println("waiter got the lock");
                } finally {
                    gate.unlock();
                }
            } catch (InterruptedException cancelled) {
                Thread.currentThread().interrupt(); // 恢复中断标记
                System.out.println("waiter cancelled while waiting");
            }
        });

        Thread.sleep(100); // waiter 此刻正阻塞在 lockInterruptibly 上
        waiter.interrupt();
        waiter.join();
        holder.join();
        System.out.println("done");
    }
}

The two ways to wait for a lock

holder takes gate.lock() and holds it for 300 ms (Thread.sleep(300) inside its critical section). waiter waits with gate.lockInterruptibly() — the variant that can be cancelled by an interrupt while queued, which plain lock() cannot offer. Fifty milliseconds after waiter starts, main calls waiter.interrupt() while it is still blocked (the holder’s critical section runs until t=300 ms, so the wait is certainly not over).

The cancellation timeline

waiter cancelled while waiting
done

The waiter wakes in its catch (InterruptedException cancelled) arm, restores its interrupt flag with Thread.currentThread().interrupt(), and prints the cancellation line. waiter got the lock sits in the success path this run never reaches — the point of the demo is that the wait itself was abortable. After waiter.join() and holder.join(), main prints done.

The line that makes the wait cancellable

gate.lockInterruptibly();

Swapping in gate.lock() would leave the same interrupt with nothing to wake: the comment’s warning about long critical sections pinning threads forever is exactly the case this method exists for.

Interactive Tools for This Topic

FAQ

What does ReentrantLock lockInterruptibly Cancels Waiting print when run?
Run it as a complete program — the output lines carry labels such as `waiter got the lock`, `waiter cancelled while waiting`, `done`.