Does the finally block execute if the thread running the function is interrupted? Does the finally block execute if the thread running the function is interrupted? multithreading multithreading

Does the finally block execute if the thread running the function is interrupted?


According to the Java Tutorials, "if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues."

Here's the full passage:

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. 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. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

class Thread1 implements Runnable {    @Override    public void run() {        try {            Thread.sleep(10000);        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            System.out.println("finally executed");        }    }}

...

t1.start();t1.interrupt();

It prints - finally executed


A Thread Interrupt in Java is just setting a flag. It doesn't cause anything special to happen to currently executing code, or affect the flow of control.

If your thread is engaged in, or attempts to enter, an operation that throws InterruptedException, then the exception is thrown from the point where that method is invoked and if it's inside a try block, the finally will execute before the exception leaves just like normal.


In the comments to the answer, @Risadinha asked very valid question about whether code in finally block gets executed if we restore interruption flag inside catch block by calling Thread.currentThread().interrupt().

Here is small code snippet to test:

final SomeContext context = new SomeContext();Thread thread = new Thread() {    @Override    public void run() {        try {            Thread.sleep(10000);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        } finally {            // this code gets executed even though            // we interrupt thread in catch block.            context.value = 9;          }    }};thread.start();thread.interrupt();thread.join(); // need to wait for thread code to completeassertEquals(context.value, 9); // values are the same!

SomeContext class code:

class SomeContext {    public volatile int value = 10;}