Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best place for shut down hook

Tags:

java

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;
            }
        }));
like image 811
klo Avatar asked Dec 12 '22 21:12

klo


1 Answers

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.

like image 54
Marko Topolnik Avatar answered Dec 29 '22 01:12

Marko Topolnik