Capture Ctrl + C in Java

Is it possible to catch the Ctrl + C signal in a java command line application? I want to clear some resources before the program ends.

+71
java command-line
Oct 23 '09 at 7:49
source share
2 answers

You can attach a shutdown quota to the VM, which starts whenever the VM shuts down:

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally when the last non-daemon thread exits or when the exit method is called (equivalently, System.exit) or

  • The virtual machine terminates in response to a user interruption, for example, entering Ctrl + C or a system-wide event, such as logging out or shutting down the system.

The stream you pass as the terminating hook must follow a few rules, so read the related documentation carefully to avoid any problems. This includes thread safety, quick thread termination, etc.

In addition, as Jesper commentator notes, terminating hooks are guaranteed to start when the virtual machine is shut down normally, but if the VM process terminates by force, they do not. This can happen if the inline code spins or if you force the process to kill -9 ( kill -9 , taskkill /f ).

But in these scenarios, all bets are turned off anyway, so I would not think too much about it.

+82
Oct 23 '09 at 7:52
source share

Just for quick console testing ...

 Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { Thread.sleep(200); System.out.println("Shutting down ..."); //some cleaning up code... } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } } }); 
+25
04 Oct '15 at 13:37
source share



All Articles