Java Concurrency Interview

Locks, conditions and AQS question 44 of 180 junior

Why is lock() outside try and unlock() inside finally the required shape?

The idiom is exact, and both deviations are bugs:

lock.lock();              // outside the try
try {
    ...
} finally {
    lock.unlock();        // always runs
}

Put lock() inside the try and a failure to acquire (an Error, or an interrupt with lockInterruptibly) still runs the finally, which calls unlock() on a lock this thread does not own: IllegalMonitorStateException, masking the original failure. Put unlock() outside the finally and any exception in the body leaks the lock permanently, which is a hang rather than a crash, in production, at 3am.

locks idiom

Quiz yourself on Locks, conditions and AQS Suggest a correction