Question

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.

Was it helpful?

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().

OTHER TIPS

It is quite hard to bypass the finally block even if you want to.
For more details on when this could happen check these for example.

Does a finally block always run?

What are the circumstances under which a finally {} block will NOT execute?

The finally block will get executed when the try finishes. It doesn't care thread is suspended or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top