Proper mechanism for parent thread to cleanUp long-running child threads...
posted 8 years ago
I have main program in a class that spawns some number of child threads and starts them in a loop:
Each of the child threads will run forever (assuming no critical errors), and they have resources like database connections, MQ resources, etc. that should be closed. I have already added code (using the Runtime addShutdownHook() method) to let the main program shut down gracefully from a Ctrl-C (for example), but what is the proper way for the parent thread to shut down the children? Join() isn't going to work, since by themselves, the child threads never complete on their own.
The proper way is for the child threads to respond to being interrupted by cleaning themselves up and terminating. Then all the parent thread has to do is to call the interrupt() method of each of the child threads.