Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: got shutdown NCCE/CS from ERR09-J

...

Code Block
bgColor#ffcccc
public class CreateFile {
  public static void main(String[] args) throws FileNotFoundException {
    final PrintStream out = new PrintStream( new BufferedOutputStream(
                                        new FileOutputStream("foo.txt")));
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
          out.close();
        }
      }));
    out.println("hello");
    Runtime.getRuntime().halt(1);
  }
}

Noncompliant Code Example (Unclean Shutdown)

When a user forcefully exits a program by pressing the ctrl + c key or by using the kill command, the JVM terminates abruptly. Although this event cannot be captured, the program should nevertheless perform any mandatory clean-up operations before exiting. This noncompliant code example fails to do so.

Code Block
bgColor#FFcccc

public class InterceptExit {
  public static void main(String[] args) {
    System.out.println("Regular code block");
    // Abrupt exit such as ctrl + c key pressed
    System.out.println("This never executes");
  }
}

Compliant Solution (addShutdownHook())

Use the addShutdownHook() method of java.lang.Runtime to assist with performing clean-up operations in the event of abrupt termination. The JVM starts the shutdown hook thread when abrupt termination is initiated; the shutdown hook runs concurrently with other JVM threads.

Wiki Markup
According to the Java API \[[API 2006|AA. Bibliography#API 06]\] Class {{Runtime}}, method {{addShutdownHook}}

A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. Once the shutdown sequence has begun it can be stopped only by invoking the halt method, which forcibly terminates the virtual machine. Once the shutdown sequence has begun it is impossible to register a new shutdown hook or de-register a previously-registered hook.

Some precautions must be taken because the JVM is in a sensitive state during shutdown. Shutdown hook threads should:

  • be light-weight and simple
  • be thread safe
  • hold locks when accessing data and release those locks when done
  • Wiki Markup
    lack reliance on system services, as the services themselves may be shutting down (for example, the logger may shutdown from another hook). Instead of one service it may be better to run a series of shutdown tasks from one thread by using a single shutdown hook \[[Goetz 2006|AA. Bibliography#Goetz 06]\].

This compliant solution shows the standard method to install a hook.

Code Block
bgColor#ccccff

public class Hook {
  public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
        hookShutdown();
      }
    });
		
   // ...
  }

  public static void hookShutdown() {
    // Log shutdown and close all resources
  }
}

The JVM can abort for external reasons, such as an external SIGKILL signal (UNIX) or the TerminateProcess call (Microsoft Windows), or memory corruption caused by native methods. Shutdown hooks may fail to execute as expected in such cases, because the JVM cannot guarantee that they will be executed as intended.

Risk Assessment

Using Runtime.halt() in place of Runtime.exit() may not perform necessary cleanup, potentially leaving sensitive data exposed or leaving data in an inconsistent state.

...