How does CTRL-C work with Java program
Asked Answered
A

2

14

When I press ctrl-c in console in what sequence are application threads stopped and shutdown hooks called?

Amadavat answered 11/7, 2012 at 14:59 Comment(1)
to quote the docs:When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. thus we can gather shutdown hooks are always called first regardless, which makes sense or what would be the point of such a hook if threads are shutdown 1st? To tell a user his data is goneTieshatieup
S
12

According to the javadocs, the registered shutdown hooks are called in an unspecified order when the JVM starts shutting down; e.g. in response to a CTRL-C.

Application threads are not "stopped" in any well defined way. Indeed, they could continue running up right until the process exits.

If you want your threads to be shut down in an orderly fashion, you need to do something in a shutdown hook to cause this to happen. For example, a shutdown hook could call Thread.interrupt() to tell worker threads to stop what they are doing ... and call join() to make sure that it has happened.

Secular answered 11/7, 2012 at 16:3 Comment(3)
Caution; Thread.join() can cause a deadlock during shutdown waiting for a thread that doesn't respect interruption. It's a good idea to use Thread.join(long) with a reasonable timeout to ensure that misbehaving threads don't block process exit.Faugh
Good point. However, if you do have a thread that doesn't respond correctly to an interrupt, and you pull the plug on the JVM regardless, then there is a risk that something might be trashed. So, IMO, a better approach is to find and fix the cause of the "deadlock"; i.e. change the offending thread to deal with interrupts properly.Secular
Can I assume that this means the main thread will not be interrupted unless you manually interrupt it or try to terminate it inside the shutdown hook?Aspia
F
5

I know that you can specify what should happen when Ctrl-C is being hit by adding a shutdown hook. But I'm not sure in what order.

private static void createShutDownHook()
{
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable()
    {

        @Override
        public void run()
        {
            System.out.println();
            System.out.println("Thanks for using the application");
            System.out.println("Exiting...");

        }
    }));
}
Femineity answered 11/7, 2012 at 15:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.