RSS RSS feed | Atom Atom feed
Popular Articles: Tom Riddle's Magical Diary | AJAX Lego Robot | AJAX CAPTCHA | SQL Multisets

Catching Control-C in Java

A short code snippet, demonstrating the use of Runtime.getRuntime().addShutdownHook().

RunWhenShuttingDown.run() below will run whenever the program is running and either Ctrl-C is pressed, loging off/shutingdown the computer, or clicking the X in the upper right hand corner.

public class CtrlC { //~ Member variables -------------------------------------------------------------------------- private volatile boolean keepOn = true; //~ Inner Classes ----------------------------------------------------------------------------- public class RunWhenShuttingDown extends Thread { public void run() { System.out.println("Control-C caught. Shutting down..."); keepOn = false; try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } //~ Methods ----------------------------------------------------------------------------------- public void runProgram() throws InterruptedException { Runtime.getRuntime().addShutdownHook(new RunWhenShuttingDown()); while(keepOn) { System.out.println("running..."); Thread.sleep(1000); } System.out.println("Stopped running."); } public static void main(String[] args) throws InterruptedException { new CtrlC().runProgram(); } }
slashdot digg del.icio.us technorati [more]



Re: Catching Control-C in Java

Very concise example.

Note that keepOn should be volatile.

Otherwise, compiler could hoist it out of the while loop.

Re: Catching Control-C in Java

Thanks. Example has been updated.

Re: Catching Control-C in Java

What is the sleep() for?

Re: Catching Control-C in Java

try it and see

Re: Catching Control-C in Java

Thanks for the example. It really helped (specially the sleep() thing...)

Re: Catching Control-C in Java

Can you keep running the program after consuming "Ctrl+C" key combination? If that is possible I will be very much interested.

Add a comment Send a TrackBack