This section provides a tutorial example on how to shutdown or terminate the JVM instance using exit() or halt() method.
There are two ways to terminate the JVM instance from the running application:
Calling the exit() method, which initiates the JVM normal shutdown sequence:
run all registered shutdown hooks; run all uninvoked finalizers; then end the JVM instance.
Calling the halt() method, which ends the JVM instance immediately.
Here is tutorial example program testing exit() and halt() methods:
/**
* RuntimeShutdown.java
* Copyright (c) 2010 by Dr. Herong Yang, herongyang.com
*/
class RuntimeShutdown {
public static void main(String[] a) {
java.io.PrintStream out = System.out;
Runtime rt = Runtime.getRuntime();
String opt = a[0];
out.println("Adding a shutdown hook...");
rt.addShutdownHook(new MyShutdownHook());
if (opt.equals("exit")) {
out.println("Asking JVM to shutdown...");
rt.exit(0);
} else if (opt.equals("halt")) {
out.println("Asking JVM to terminate...");
rt.halt(0);
} else {
out.println("Putting the application to sleep...");
try {Thread.sleep(1000*60*60);}
catch (InterruptedException e) {}
}
}
public static class MyShutdownHook extends Thread {
public void run() {
System.out.println("Running my shutdown hook...");
}
}
}
When executed on my Windows XP system with JDK 1.6.0,
I got this result:
C:\herong\jvm>java RuntimeShutdown exit
Adding a shutdown hook...
Asking JVM to shutdown...
Running my shutdown hook...
C:\herong\jvm>java RuntimeShutdown halt
Adding a shutdown hook...
Asking JVM to terminate...
The test result confirms that:
My shutdown hook was executed during the JVM shutdown sequence initiated by the exit() method.
The JVM instance was terminated immediately when calling the halt() method. My shutdown hook was not executed.
Shutting down and terminating the JVM instance can also be initiated with Windows system tools
like pressing Ctrl-C or using the Task Manager. To test these tools, you can run my test program with the third option:
C:\herong\jvm>java RuntimeShutdown sleep
Adding a shutdown hook...
Putting the application to sleep...
(press Ctrl-C on the console)
Running my shutdown hook...
C:\herong\jvm>java RuntimeShutdown sleep
Adding a shutdown hook...
Putting the application to sleep...
(terminate the Java process using Windows Task Manager)
As you can see from the test result:
Pressing Ctrl-C is equivalent to calling exit().
Terminate the Java process using Windows Task Manager is equivalent to calling halt().