Catch a few Ctrl + C keys in Java to make graceful and forced shutdowns

In my Java console application, I catch the Ctrl + C key and add a thread to do a graceful shutdown using Runtime.getRuntime (). addShutdownHook ()

In this thread, I process all the work in progress in some internal queues and gracefully exit my application, which is usually what I want.

However, sometimes an application may have internal queues that take time to process (several minutes), so I would like to press Ctrl + C a second time to force exit the application.

I have seen other applications work this way, but I cannot find how to catch the second Ctrl + C in Java?

+4
source share
1 answer

Warning, this is not what you should do. Common reasons apply to prevent the use of the solar pack. Think three times before using this in real code. At a minimum, access to signal processing should be done with reflection and return to registering a regular interrupt at shutdown. I left this for short.

So all hope will leave you, you who enter here:

import java.util.concurrent.atomic.AtomicBoolean; import sun.misc.Signal; import sun.misc.SignalHandler; public class Sigint { private static void prepareShutdownHandling() { // This would be the normal shutdown hook final Thread shutdown = new Thread() { @Override public void run() { // Simulate slow shutdown for (int i = 0; i < 10; i++) { System.out.println("Normal shutdown running"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(System.err); } } System.out.println("Normal shutdown finished"); System.exit(0); } }; Signal.handle(new Signal("INT"), new SignalHandler() { private AtomicBoolean inShutdown = new AtomicBoolean(); public void handle(Signal sig) { if (inShutdown.compareAndSet(false, true)) { // Normal shutdown shutdown.start(); } else { System.err.println("Emergency shutdown"); System.exit(1); } } }); } public static void main(String args[]) { prepareShutdownHandling(); while (true) { System.out.println("Main program running"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(System.err); } } } } 
+2
source

Source: https://habr.com/ru/post/1493603/


All Articles