Understanding System.exit() vs Runtime.getRuntime().halt() in Java
This tutorial explains the differences between Java's System.exit() and Runtime.getRuntime().halt(), detailing their shutdown sequences, impact on shutdown hooks and finalizers, providing code examples and test cases, and offering guidance on when to use each method safely.
Overview: This tutorial explores System.exit() and Runtime.getRuntime().halt() and compares the two methods.
System.exit() stops the running JVM but first invokes the shutdown sequence, which runs registered shutdown hooks and, if finalization-on-exit is enabled, any pending finalizers before terminating the JVM.
public static void exit(int status)A non‑zero status code indicates abnormal termination.
Runtime.getRuntime().halt() forcibly terminates the JVM without triggering the shutdown sequence; therefore neither shutdown hooks nor finalizers are executed.
public void halt(int status)A non‑zero status code also signals abnormal termination.
Example: A Java class registers a shutdown hook and provides two methods—processAndExit() that calls System.exit(0) and processAndHalt() that calls Runtime.getRuntime().halt(0). Test cases demonstrate that the shutdown hook runs when exit is used but not when halt is used.
public class JvmExitAndHaltDemo {
private static Logger LOGGER = LoggerFactory.getLogger(JvmExitAndHaltDemo.class);
static {
Runtime.getRuntime()
.addShutdownHook(new Thread(() -> {
LOGGER.info("Shutdown hook initiated.");
}));
}
public void processAndExit() {
process();
LOGGER.info("Calling System.exit().");
System.exit(0);
}
public void processAndHalt() {
process();
LOGGER.info("Calling Runtime.getRuntime().halt().");
Runtime.getRuntime().halt(0);
}
private void process() {
LOGGER.info("Process started.");
}
} @Test
public void givenProcessComplete_whenExitCalled_thenTriggerShutdownHook() {
jvmExitAndHaltDemo.processAndExit();
} @Test
public void givenProcessComplete_whenHaltCalled_thenDoNotTriggerShutdownHook() {
jvmExitAndHaltDemo.processAndHalt();
}When to use each: System.exit() is appropriate when you need an orderly shutdown, allowing hooks to run and returning a status code, while halt is useful for forcing termination when exit is blocked or when immediate shutdown is required. Both methods invoke SecurityManager.checkExit, so a custom security policy can prevent their use.
Summary: The tutorial demonstrates the behavior of System.exit() and Runtime.getRuntime().halt(), provides practical examples, and discusses best practices for their usage.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.