// Demo showing a sample use of a shutdown hook. Shutdown // hooks replace using finializers in Java. // // Written 9/2006 by Wayne Pollock, Tampa Florida USA. import java.util.*; public class ShutdownHookDemo { static List resourceList = new ArrayList(); public static void main( String [] args ) throws Exception { Thread shutdownHook = new Thread() { public void run () { System.out.println( "Running shutdown hook:" ); // for each item that needs cleanup steps, do them now. // Note in real life you probably have a list of objects, // each with some "cleanup" code to run. Each object, in // its constructor can register a shutdown hook. Then you // don't need a list as used here. for ( String name : resourceList ) System.out.println( "\tCleaning up resource " + name ); } }; Runtime currentJRE = Runtime.getRuntime(); currentJRE.addShutdownHook( shutdownHook ); // Now do stuff, knowing any resources will be cleaned up at exit: resourceList.add("Blossom" ); resourceList.add("Buttercup" ); resourceList.add("Bubbles" ); System.out.print( " Type 'x' to exit, 'e' to cause exception, " + "or 'p' to pause: " ); Scanner in = new Scanner( System.in ); String choice = in.next(); switch ( choice.charAt(0) ) { case 'x': case 'X': System.exit( 0 ); case 'e': case 'E': throw new Exception( "abort" ); } // Sleep for a few seconds to allow user to hit ctl+c: try { Thread.sleep( 8*1000 ); } catch (InterruptedException e) {} } }