Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 464
marc wellman Avatar asked Dec 25 '13 18:12

marc wellman


1 Answers

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

like image 184
Malcolm Avatar answered Oct 10 '22 09:10

Malcolm