Share this page 

Trap JVM shutdownTag(s): Varia

The Java virtual machine shuts down in response to two kinds of events:
  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked.
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.


public class TrapBreak {

public static void main(String args[]) throws Exception{
    new TrapBreak().doit();

   public void doit() throws Exception{
       Runtime.getRuntime().addShutdownHook(new Thread() {
              public void run() {
                    System.out.println("*** END ***");

       while(true) { Thread.sleep(100); System.out.print("."); }

To test it out on Windows, in DOS window, start the class with

C:\temp> java TrapBreak >out.log
Now close the DOS window by clicking on the upper-right X.

Now check the out.log file, you will find "*** END ***" written by our ShutdownHook.

..................*** END ***