Kill it with an uncaught exception within the finally
block, or kill the overall JVM (which kills the thread, among other things).
There is no good reason to stop the execution of a finally
block except poor design. If it's not supposed to run every time, then don't put it in a finally
block.
Using the below test code, I run two different scenarios to see what happens when killing the Thread
:
- Start the
Thread
and sleep
the main thread for 2 seconds. Within the Thread
, pretty much immediately enter the finally
block and then sleep for 5 seconds. Once the main thread is finished waiting, kill the Thread
using stop
.
- Start the
Thread
and sleep 2 seconds. Within the Thread
, sleep 5 seconds before entering the finally
block and then sleep some more within the finally
to give it a chance to be killed.
In the first case, the result is that the finally
block stops executing.
In the second case, the result is that the finally
block executes completely, and on the Thread
that was stop
ped no less.
Output (note the name of the current thread added for all output):
thread-starting [main]
trying [Thread-0]
catching [Thread-0]
finally-sleeping [Thread-0]
thread-stopped [main]
[main]
thread-starting [main]
trying-sleeping [Thread-1]
thread-stopped [main]
finally-sleeping [Thread-1]
finally-done [Thread-1]
Code:
public class Main
{
public static void main(String[] args)
{
testThread(new TestRunnable());
println("");
testThread(new TestRunnable2());
}
private static void testThread(Runnable runnable)
{
Thread testFinally = new Thread(runnable);
println("thread-starting");
testFinally.start();
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
println("main-interrupted...");
}
testFinally.stop();
println("thread-stopped");
}
private static class TestRunnable implements Runnable
{
@Override
public void run()
{
try
{
println("trying");
throw new IllegalStateException("catching");
}
catch (RuntimeException e)
{
println(e.getMessage());
}
finally
{
println("finally-sleeping");
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
println("finally-interrupted");
}
println("finally-done");
}
}
}
private static class TestRunnable2 implements Runnable
{
@Override
public void run()
{
try
{
println("trying-sleeping");
Thread.sleep(5000);
}
catch (InterruptedException e)
{
println("trying-interrupted");
}
finally
{
println("finally-sleeping");
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
println("finally-interrupted");
}
println("finally-done");
}
}
}
private static void println(String line)
{
System.out.printf("%s [%s]%n", line, Thread.currentThread().getName());
System.out.flush();
}
}