Java Hard Puzzle | Puzzle 39: Hello, Goodbye

This program adds an unusual twist to the usual Hello world program. What does it print?


package javapuzzlers;

public class HelloGoodbye {
public static void main(String[] args) {
try {
System.out.println("Hello world");
System.exit(0);
} finally {
System.out.println("Goodbye world");
}
}
}


Output:
$javac HelloWorld.java
$java  HelloWorld
Hello world

Solution:
It is true that a finally block is executed when a try block completes execution whether normally or abruptly. In this program, however, the try block does not complete execution at all. The System.exit method halts the execution of the current thread and all others dead in their tracks. The presence of a finally clause does not give a thread special permission to continue executing. When System.exit is called, the virtual machine performs two cleanup tasks before shutting down. First, it executes all shutdown hooks that have been registered with Runtime.addShutdownHook. This is useful to release resources external to the VM. Use shutdown hooks for behavior that must occur before the VM exits. The following version of the program demonstrates this technique, printing both Hello world and Goodbye world, as expected:

public class HelloGoodbye {
public static void main(String[] args) {
System.out.println("Hello world");
Runtime.getRuntime().addShutdownHook(
new Thread() {
public void run() {
System.out.println("Goodbye world");
}
});
System.exit(0);
}
}


Comments