I have a main() method that calls a Thread class and starts a thread. This thread has a while(threadBool) loop, so I need to stop it when I exit the program ( by setting threadBool to false). Where is the best place to place addShutdownHook()? In the main() method
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
class.threadBool=false;
}
}));
or in the same class that started this thread
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
threadBool=false;
}
}));
The best place is nowhere at all. Shutdown hooks are only a last-resort effort due to an unexpected interuption of the program to salvage what can be salvaged.
You should instead organize your code so that there is a cleanly defined entry point, main body, and exit point. You can then stop your thread at the exit point.