Operations 5 min read

How to Implement Graceful Restart of the JVM

This article explains the three JVM shutdown methods, how to use ShutdownHook and custom SignalHandler for cleanup, and outlines a step‑by‑step graceful restart process using kill -12, kill -15, and kill -9 signals, with sample scripts and references.

Zhuanzhuan Tech
Zhuanzhuan Tech
Zhuanzhuan Tech
How to Implement Graceful Restart of the JVM

JVM can be terminated in three ways: normal shutdown (last non‑daemon thread ends, System.exit, or SIGINT/SIGTERM), forced shutdown (Runtime.halt or kill -9), and abnormal shutdown (RuntimeException, OOM, etc.).

Using Runtime.getRuntime().addShutdownHook(handleThread); you can register a shutdown hook that runs when the JVM exits normally or due to an exception, allowing cleanup work. All registered hooks are executed concurrently and unordered when the JVM shuts down.

The shutdown hook responds to signals SIGHUP (1), SIGINT (2) and SIGTERM (15); avoid using kill -9 because the hook will not run. Keep hooks short and thread‑safe because they may be invoked by multiple threads.

A custom SignalHandler can be implemented to handle specific signals, for example:

class MySignalHandler implements SignalHandler {
    public static void listenTo(String name) {
        Signal signal = new Signal(name);
        Signal.handle(signal, new MySignalHandler());
    }
    public void handle(Signal signal) {
        System.out.println("Signal: " + signal);
        if (signal.toString().trim().equals("SIGTERM")) {
            System.out.println("SIGTERM raised, terminating...");
            System.exit(1);
        }
    }
}

Because signal handling runs in separate threads, the handler must be thread‑safe.

Graceful shutdown procedure:

Send kill -12 and wait 10 seconds; a custom SignalHandler processes the signal, allowing the service to stop accepting new requests and finish in‑flight work.

Send kill -15 and wait another 10 seconds; registered shutdown hooks run concurrently to release resources.

If the JVM is still alive, send kill -9 to force termination.

A sample startup script (main.sh) demonstrates start, stop, restart, status and kill commands for managing the JVM process.

References include a StackOverflow discussion on handling SIGKILL in Java and a Juejin article on service graceful shutdown.

JavaJVMGraceful ShutdownShutdownHookSignalHandlerLinux Signals
Zhuanzhuan Tech
Written by

Zhuanzhuan Tech

A platform for Zhuanzhuan R&D and industry peers to learn and exchange technology, regularly sharing frontline experience and cutting‑edge topics. We welcome practical discussions and sharing; contact waterystone with any questions.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.