Can I make sure my timer-started threads run to completion if the VM is shutdown by Control-C?

1k Views Asked by At

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:

Catching Ctrl+C in Java

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?

1

There are 1 best solutions below

0
On

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 the TimerTasks aren't directly exposed to you, but you could put something like this in your class:

private static List<Thread> timerThreads = new LinkedList<Thread>();

And then something like this at the very top of the TimerTask.run() method:

timerThreads.add(Thread.currentThread());

And then something like this in the shutdown hook:

try {
    for (Thread t : timerThreads) {
        t.join();
    }
} catch (InterruptedException e) {
    // handle it somehow
}

This guarantees that all the active threads will run to completion. It is, however, not necessarily a good idea. To quote the API documentation:

Shutdown hooks run at a delicate time in the life cycle of a virtual machine and should therefore be coded defensively. They should, in particular, be written to be thread-safe and to avoid deadlocks insofar as possible. [...] Shutdown hooks should also finish their work quickly. When a program invokes exit the expectation is that the virtual machine will promptly shut down and exit. When the virtual machine is terminated due to user logoff or system shutdown the underlying operating system may only allow a fixed amount of time in which to shut down and exit. It is therefore inadvisable to attempt any user interaction or to perform a long-running computation in a shutdown hook.