[To advertise Java(tm) Events here, contact!]

by example!

New @

  gb  In-house search engine for better results!

  gb  Get updates with the

 Browse Categories 
 Ask a Java Question 
  For Java Tips & Tricks, subscribe to the newsletter!
Search Java Q&A, Links, API's:   adv 

How do I trap CTRL-C in my Java app?
The method addShutdownHook() of the java.lang.Runtime class provides a way of trapping a shutdown of the virtual machine. Please not that this method was added since java version 1.3.

The method expects one argument and that is a Thread object. This thread will be started when the virtual machine terminates. The only way this code will not be executed is when you use the method Runtime.halt().
After you have added a Shutdown hook, it is also possible to remove it with the equivalent method removeShutdownHook(). Its parameter should be the same as the one passed in addShutdownHook.

The following code illustrates an example that makes use of the addShutdownHook method.

// The Shutdown class is a sample class to illustrate the
// use of the addShutdownHook method
class Shutdown {
private Thread thread = null;

public Shutdown() {
thread = new Thread("Sample thread") {
public void run() {
while (true) {
System.out.println("[Sample thread] Sample thread speaking...");
try {
} catch (InterruptedException ie) {
System.out.println("[Sample thread] Stopped");

public void stopThread() {

// The ShutdownThread is the thread we pass to the
// addShutdownHook method
class ShutdownThread extends Thread {
private Shutdown shutdown = null;

public ShutdownThread(Shutdown shutdown) {
this.shutdown = shutdown;

public void run() {
System.out.println("[Shutdown thread] Shutting down");
System.out.println("[Shutdown thread] Shutdown complete");

// And finally a Main class which tests the two classes
// We let the sample thread run for 10 seconds and then
// force a Shutdown with System.exit(0). You may stop the
// program early by pressing CTRL-C.
public class Main {
public static void main(String [] args) {
Shutdown shutdown = new Shutdown();
try {
Runtime.getRuntime().addShutdownHook(new ShutdownThread(shutdown));
System.out.println("[Main thread] Shutdown hook added");
} catch (Throwable t) {
// we get here when the program is run with java
// version 1.2.2 or older
System.out.println("[Main thread] Could not add Shutdown hook");

try {
} catch (InterruptedException ie) {

Further Information
Author of answer: Sykora Joeri

Comments to this answer are only viewable by members. Login or become a member!

Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.