Ever wanted to catch O/S Interrupts in your Java code? Things like CTRL-C on Windows or various SIGs on your fave brand of Unix. Well it turns out you can!

A friend from work tipped me off to a feature introduced in JDK 1.3 where you can call Runtime.addShutdownHook(Thread yourHook). You pass in the thread unstarted, and when the VM gets a shutdown signal, it’ll start your thread.


        Runtime rt = Runtime.getRuntime();

        rt.addShutdownHook(new Thread() {

            public void run() {

                System.out.println("Ah-ha! You killed it!");

                System.out.flush();

            }

        });

Neat, huh! For more info check out http://java.sun.com/j2se/1.3/docs/guide/lang/enhancements.html#hooks