Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does CTRL-C work with Java program

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

like image 333
user590444 Avatar asked Jul 11 '12 14:07

user590444


People also ask

What does Ctrl C do in Java?

ctrl c is used to kill a process. It terminates your program.

What is Ctrl D in Java?

Ctrl+D also causes the terminal to make buffered input available, or, if nothing is buffered, to terminate the input. Asking for a program to do something on Ctrl+D is essentially asking it to do something when it reads all available input (and more may become available later).


1 Answers

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.

like image 64
Stephen C Avatar answered Sep 20 '22 12:09

Stephen C