Best place to stop the hook

I have a main () method that calls the Thread class and starts the 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 add 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; } })); 
+4
source share
1 answer

A better place does not exist anywhere. The final hooks are only the last action due to an unexpected interruption in the program to save what can be saved.

Instead, you should organize your code so that there is a clearly defined entry point, main element, and exit point. Then you can stop the flow at the exit point.

+13
source

Source: https://habr.com/ru/post/1439683/


All Articles