Thursday, June 19, 2008

Runtime.exit() vs Runtime.halt() in Java

Difference between Runtime.exit() and Runtime.halt() in Java

Runtime.exit() - public void exit(int status) - this method causes the shutdown sequence of the underlying JVM to be invoked. This method indicates an abnormal termination of the JVM and the parameter status may be used as a staus code for the various abnormal circumstances which caused the termination of the JVM process.

The shutdown sequence of a JVM is consists of two phases - One, execution of all registered shutdown hooks (read more about them in this article - Shutdown Hooks in Java >>) and Two, execution of all uninvoked finalizers (if finalization-on-exit is enabled) and then halting the JVM process.

If this method is called once the shutdown of the JVM has already started then this method will block indefinitely in case any registered shutdown hook is still under execution. Otherwise, if all the registered shutdown hooks have already completed their execution and if the finalization-on-exit is enabled, then a non-zero status code as the parameter will simply halt the JVM process whereas a zero status code will causes the method to be blocked indefinitely.

This method can be conveniently called by using the more popular System.exit() method as well. Since, System.exit(n) will be internally converted into RunTime.getRuntime().exit(n) only, hence it hardly matters which one of the two you choose. Choosing the former may seem to be little more convenient while the latter will skip the conversion step.

Runtime.halt() - public void halt(int status) - this method terminates the underlying JVM process forcibly. That means the invokation of this method will not initiate the shutdown sequence and hence no shutdown hooks or finalizers will be executed. status as a parameter serves the same purpose as it does in the Runtime.exit() method - it may be used to indicate the status code of the abnormal situation that invoked this Runtime.halt() method.

Difference between Runtime.exit() and Runtime.halt()

You might have noticed so far that the difference between the two methods is that Runtime.exit() invokes the shutdown sequence of the underlying JVM whereas Runtime.halt() forcibly terminates the JVM process. So, Runtime.exit() causes the registered shutdown hooks to be executed and then also lets all the uninvoked finalizers to be executed before the JVM process shuts down whereas Runtime.halt() simply terminates the JVM process immediately and abruptly.


No comments: