Quick revision
The short answer
The early return is not the problem, because finally still unlocks. The problem is that lock() is inside the try: if acquiring the lock fails, for example when this is changed to lockInterruptibly() and the thread is interrupted while waiting, finally calls unlock() on a lock the thread does not hold. That throws IllegalMonitorStateException, which replaces and hides the original exception. Calling lock() on the line immediately before try fixes it, because finally then only runs after the lock was really acquired.
What to remember
In this answer, we saw that the early return is harmless because finally always unlocks a lock that was really acquired. The bug is the acquisition inside the try: when it fails, for example lockInterruptibly() being interrupted, finally calls unlock() without holding the lock, which throws IllegalMonitorStateException and hides the original exception, and with a reentrant outer hold it can even silently release someone else's protection. Calling the acquisition directly before try fixes all of this, and static analysis rules can enforce the pattern in the build.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The early return is not the problem, because finally still unlocks. The problem is that lock() is inside the try: if acquiring the lock fails, for example when this is changed to lockInterruptibly() and the thread is interrupted while waiting, finally calls unlock() on a lock the thread does not hold. That throws IllegalMonitorStateException, which replaces and hides the original exception. Calling lock() on the line immediately before try fixes it, because finally then only runs after the lock was really acquired.
Why this question is asked
This is a small bug that code reviewers and static analysis tools catch all the time, and it is worth understanding properly because it is invisible in normal runs. The code works perfectly until the one day acquisition fails, and then the error report points at the wrong place. Interviewers ask it to see whether we reason about every path through try and finally, not just the happy path. In this answer, we will recap how try and finally interact with a lock, check that the early return is fine, walk through what happens when lock() fails, see the even quieter failure with a reentrant hold, and then fix it and look at how tools enforce the pattern.
1A Quick Recap of the Code
Here is the code from the question, formatted so we can follow each path. A ReentrantLock, unlike synchronized, is not released automatically, so the finally block is what guarantees release.
A finally block runs whenever control leaves the try block, whether by reaching its end, by a return, or by an exception. That rule is what makes the unlock reliable, and it is also what causes the bug.
2Checking the Early Return First
The question invites us to worry about the return statement, so let us settle it. When valid(order) is false, the method returns from inside the try. Before the method actually returns, the finally block runs and calls unlock(). The lock was acquired on the previous line, so the unlock is correct and the hold count goes back to zero. The early return is fine.
The same is true for an exception thrown by valid() or process(): the lock is held, finally releases it, and the exception continues upwards unchanged.
3What Happens When lock() Fails
Now consider the path the author did not think about: the exception is thrown by the acquisition itself. With plain lock() that is rare, since lock() does not throw checked exceptions and ignores interrupts. But code changes. A common change is switching to lockInterruptibly(), so that shutdown can cancel waiting threads. Then an interrupt while waiting throws InterruptedException out of the acquisition, before the lock is held.
- Enter try
- lock() succeeds?YesBody runs, finally unlocks correctlyNoException from lock()
- finally calls unlock()the thread is not the owner
- IllegalMonitorStateExceptionreplaces the original exception
4 steps in order. Play them, or step through them one at a time.
Only the failure path is wrong, which is why normal testing never shows it.
Notice what happened. The InterruptedException starts to travel up, finally runs, and unlock() throws IllegalMonitorStateException because the current thread is not the owner. An exception thrown from a finally block replaces the one that was in flight, so the caller sees IllegalMonitorStateException and the interrupt is lost. Anyone debugging this looks for a locking bug, when the real event was a cancelled thread. The interrupt status is also cleared by the time the InterruptedException is thrown, so the shutdown request disappears completely.
4An Even Quieter Failure With Reentrant Holds
There is a second variant that throws nothing at all. ReentrantLock counts holds per thread. Suppose an outer method already holds the lock and calls this method, and the inner acquisition fails, for example a timed or interruptible acquire written the same way. The thread is the owner, from the outer hold, so the stray unlock() succeeds and quietly releases the outer method's hold.
The outer method then continues to run what it believes is a protected critical section, while other threads are free to enter. Nothing is logged, and data can be corrupted. This is the strongest argument for the rule: unlock() must be paired exactly with a successful acquisition, never with an attempt.
5The Fix: Acquire Immediately Before try
Move the acquisition out of the try, to the line directly before it. If the acquisition throws, the try has not started yet, so finally does not run and the original exception reaches the caller unchanged. If it succeeds, the very next thing is the try, so there is no gap in which an exception could leave the lock held.
Notice that nothing should sit between the acquisition and the try. Even a harmless-looking log statement there could throw and leave the lock held forever, which is the opposite bug.
6Letting Tools Enforce the Pattern
Because the bug only appears on a rare path, people should not have to spot it by eye. Common static analysis tools have rules for it: Error Prone has a check that flags a lock() call that is not immediately followed by try, SonarQube has a rule that locks must be released on all paths, and SpotBugs reports locks that may not be released (check your tool version for the exact rule names). Enabling one of them in the build makes the correct shape the only shape that passes review.
When the extra features of ReentrantLock are not needed, a synchronized block avoids the whole class of bugs, because the JVM pairs acquisition and release for us.
7Follow-up questions
Can plain lock() ever throw?
In practice almost never. It does not respond to interrupts and declares no checked exceptions. An Error such as OutOfMemoryError or StackOverflowError is theoretically possible. The real risk is that code gets changed later to lockInterruptibly() or tryLock() while keeping the same shape, so the pattern should be correct from the start.
What should the code do with the InterruptedException?
Usually let it propagate, so the caller knows the task was cancelled. If the method cannot throw it, catch it and call Thread.currentThread().interrupt() to restore the interrupt status, so code further up still sees the cancellation request.
Why does an exception in finally hide the original one?
Java allows only one exception to propagate from a block. When finally throws, its exception replaces the pending one completely. try-with-resources records suppressed exceptions, but a plain finally does not, so the original is lost unless we catch and handle it explicitly.
8Conclusion
In this answer, we saw that the early return is harmless because finally always unlocks a lock that was really acquired. The bug is the acquisition inside the try: when it fails, for example lockInterruptibly() being interrupted, finally calls unlock() without holding the lock, which throws IllegalMonitorStateException and hides the original exception, and with a reentrant outer hold it can even silently release someone else's protection. Calling the acquisition directly before try fixes all of this, and static analysis rules can enforce the pattern in the build.
Open with
The early return is not the issue. Return from inside try still runs finally, and at that point the lock is held, so the unlock is correct. The issue is that lock is called inside the try.
Then, if they want more
If acquiring the lock fails, finally still runs and calls unlock on a lock this thread does not own. With plain lock that is rare, but if someone changes it to lockInterruptibly, an interrupt while waiting throws InterruptedException, then finally calls unlock, which throws IllegalMonitorStateException.
An exception from finally replaces the one in flight, so the caller sees a confusing lock error and the interrupt is lost.
There is also a quieter variant: if the thread already holds the lock reentrantly from an outer method and the inner acquire fails, the stray unlock succeeds and drops the outer hold, so the outer critical section is no longer protected.
The fix is to call lock on the line immediately before try, with nothing in between, so finally only runs after a successful acquisition. For tryLock, the try goes inside the true branch.
I would also turn on a static analysis rule, Error Prone or Sonar both have one, so the build enforces the pattern, and use synchronized when I do not need ReentrantLock's extra features.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "What is wrong with this code?": https://scrivio-interview-library.netlify.app/java/locks/1407c1cce7/