Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java lockInterruptibly: cancel a worker waiting for ownership

Last updated: 1 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

Lock.lockInterruptibly lets a waiting thread stop trying to acquire a lock when it is interrupted.

Keep cancellation at the wait boundary

The main thread holds a lock while a worker attempts an interruptible acquisition. It interrupts the worker before releasing ownership, so the worker exits without entering the guarded section. A latch makes the ordering visible; the final output does not depend on which core ran first.

Cancellation policy must also cover work after acquisition. A thread that already owns a lock cannot be made safe merely by interrupting it; its critical section needs cleanup and an explicit stop decision.

Track ownership precisely

Only unlock after acquisition succeeded. An InterruptedException from lockInterruptibly means this call did not acquire the lock. Preserve or propagate the cancellation decision at the task boundary instead of quietly retrying forever.

Working program

Java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;

public class InventoryLockCancellation {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock guard = new ReentrantLock();
        CountDownLatch attempting = new CountDownLatch(1);
        AtomicBoolean cancelled = new AtomicBoolean();
        guard.lock();
        Thread worker = new Thread(() -> {
            attempting.countDown();
            try {
                guard.lockInterruptibly();
                try { throw new AssertionError("unexpected ownership"); }
                finally { guard.unlock(); }
            } catch (InterruptedException stopped) {
                cancelled.set(true);
            }
        });
        try {
            worker.start();
            attempting.await();
            worker.interrupt();
            worker.join();
            System.out.println("cancelled=" + cancelled.get());
        } finally { guard.unlock(); }
    }
}

Output

Output
cancelled=true

Cost and ownership

The coordination uses constant storage and one waiting thread. There is no finite wait bound without an interrupt or a timed tryLock; production callers should decide who owns that timeout or cancellation signal.

Common Mistakes

  • Do not unlock a lock that the interrupted worker never acquired.
  • Do not swallow interruption and silently retry the same wait.
  • Do not assume interruption repairs partially completed work after ownership begins.

Read next

Java ReentrantLock: protect a complete state transition, Java cancellation: timed waits and cooperative interruption, Java Thread.interrupted clears the current thread's signal, Java conditions: protected predicates and timed waiting.

java
concurrency
lock-interruptibly
Storage details