Search code examples
javamultithreadingfinally

finally-block and thread suspension


I've noticed that in Java if the current thread is beeing suspended within a try-block the corresponding finally block is not being executed such as in

Semaphore lock = new Semaphore(0);

try {

    lock.acquire();

} finally {

// do something

}

Can this observation be generalized to the suspension of threads i.e. is it true what the Oracle doc says that it can only used to bypass return, break and continue?

Oracle doc. says:

But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.


Solution

  • The finally block will start executing when the try block finishes. Since the thread did not finish executing the try block, it can't enter the finally block. It doesn't mean that the finally block is bypassed, though. It will still get executed when the thread returns from lock.acquire().