I am writing a multi-threaded java console application that I am intending to kill via Ctrl-C. In this situation, if I have a class that encapsulates a single thread is it good practice to shutdown the child thread in the encapsulating classes finalize method?
Is it possible to get artifacts of the original application left running if you Ctrl-C the original app and all threads are not shutdown properly?
pseudo code:
public class ParentClass {
Thread childThread = new Thread(new ExampleRunnable());
@Override protected void finalize() throws Throwable {
childThread.shutdown();
}
}
public class ExampleRunnable implements Runnable {
private volatile boolean alive = false;
@Override
public void run() {
alive = true;
while(alive) {
//do some work
}
}
public void shutdown() {
alive = false;
}
}
Implementing
finalizecan have a terribly bad side-effect. Way back in the day, Java was slow and one of the reasons was the need to runfinalizeon every object ever created. Now the JVMs are smart enough to check if a non-trivialfinalizeimplementation exists rather than blindly call it on every object being collected. Having just one class implementfinalizemay not be bad, but don’t make a habit of it.If you want to do something special during a normal shutdown of the JVM, then use a shutdown hook.