Suppose I make a few calls to the following function:
public void StartTimedRuns(){
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
public void run(){
//do something that takes less than a minute
}
}, 0, 60*1000);
}
My understanding is that a bunch of threads will be running simultaneously at this point. That is, each timer instance will be spawning short-lived threads at 1-minute intervals.
Suppose I install a shutdown hook (to run when I press Control-C) per the instructions here:
The shutdown hook will cancel all the timers. (Assume that I store the timers in a class-level collection)
Can I guarantee that all the active threads will run to completion before the VM exits?
Related to this, does the shutdown hook only get called when the threads all exit?
The shutdown hook gets called when either the main thread finishes, or a keyboard interrupt via Ctrl+C occurs.
If you want to guarantee that the active threads will run to completion, you have to explicitly
join()
them in the shutdown hook. This is slightly tricky, since the threads used by theTimerTask
s aren't directly exposed to you, but you could put something like this in your class:And then something like this at the very top of the
TimerTask.run()
method:And then something like this in the shutdown hook:
This guarantees that all the active threads will run to completion. It is, however, not necessarily a good idea. To quote the API documentation: