Signals and graceful shutdown

suggest change

When running Java services in production—such as web servers, message consumers, or cloud containers (Docker/Kubernetes)—applications must gracefully terminate upon receiving termination signals (SIGTERM, SIGINT). Graceful shutdown ensures in-flight requests finish, active database transactions commit or roll back, background queues drain, and external resources close cleanly.

The JVM Shutdown Lifecycle

The Java Virtual Machine initiates shutdown under the following conditions:

  1. Normal termination: The last non-daemon thread finishes execution, or System.exit(status) is explicitly called.
  2. Operating System Signals: The process receives a SIGINT (such as Ctrl+C) or SIGTERM (sent by Kubernetes during pod eviction, docker stop, or kill <pid>).

[!CAUTION] SIGKILL (kill -9) forcefully terminates the process immediately. The OS reclaims memory and open descriptors, but the JVM cannot run any shutdown hooks or cleanup code.

Registering JVM Shutdown Hooks

The standard way to execute cleanup logic during JVM shutdown is registering an unstarted Thread with Runtime.getRuntime().addShutdownHook():

public class GracefulShutdownDemo {
    public static void main(String[] args) throws InterruptedException {
        // Register the shutdown hook
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("[Shutdown Hook] Signal received. Starting cleanup...");
            cleanupResources();
            System.out.println("[Shutdown Hook] Cleanup complete. JVM exiting.");
        }, "shutdown-hook-thread"));

        System.out.println("Application running. Press Ctrl+C or send SIGTERM to exit...");

        // Simulate application workload
        while (true) {
            Thread.sleep(1000);
        }
    }

    private static void cleanupResources() {
        try {
            // Flush buffers, release file locks, flush telemetry
            Thread.sleep(1000); // Simulate work
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

Gracefully Draining an ExecutorService

When your application manages worker thread pools, you should stop accepting new tasks and wait for queued tasks to finish before exiting:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadPoolGracefulShutdown {

    public static void shutdownGracefully(ExecutorService pool, long timeoutSeconds) {
        // Step 1: Reject new tasks
        pool.shutdown();

        try {
            // Step 2: Wait for existing tasks to complete
            if (!pool.awaitTermination(timeoutSeconds, TimeUnit.SECONDS)) {
                System.err.println("Tasks did not finish within timeout; forcing cancellation...");
                // Step 3: Cancel currently executing tasks
                pool.shutdownNow();

                // Step 4: Wait for cancelled tasks to respond to interruption
                if (!pool.awaitTermination(timeoutSeconds, TimeUnit.SECONDS)) {
                    System.err.println("Thread pool did not terminate completely.");
                }
            }
        } catch (InterruptedException ie) {
            // Preserve interrupt status and force stop
            pool.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) {
        ExecutorService workerPool = Executors.newFixedThreadPool(4);

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("Shutting down worker pool...");
            shutdownGracefully(workerPool, 5);
            System.out.println("Worker pool successfully shut down.");
        }));
    }
}

Catching Specific POSIX Signals (sun.misc.Signal)

While standard shutdown hooks handle normal shutdown, certain applications need to intercept specific signals—such as SIGHUP to reload configuration files without restarting the process:

import sun.misc.Signal;
import sun.misc.SignalHandler;

public class SignalHandlingExample {
    public static void main(String[] args) throws InterruptedException {
        // Handle SIGHUP (Configuration reload on Unix)
        Signal.handle(new Signal("HUP"), new SignalHandler() {
            @Override
            public void handle(Signal sig) {
                System.out.println("Received SIGHUP! Reloading application configuration...");
                reloadConfiguration();
            }
        });

        System.out.println("Listening for SIGHUP (kill -HUP " + ProcessHandle.current().pid() + ")");
        while (true) {
            Thread.sleep(2000);
        }
    }

    private static void reloadConfiguration() {
        // Reload config without dropping connections
    }
}

Best Practices and Rules for Shutdown Hooks

  1. Keep hooks fast: Operating systems and container orchestrators enforce hard deadlines. For example, Kubernetes default terminationGracePeriodSeconds is 30 seconds before sending SIGKILL.
  2. Hooks execute concurrently: All registered shutdown hooks start simultaneously in non-deterministic order. If resource A depends on resource B, coordinate them explicitly within a single hook.
  3. Never call System.exit() inside a hook: Once shutdown has begun, System.exit() blocks indefinitely, so the hook never finishes and the JVM stalls.
  4. Avoid deadlock: Ensure hooks do not wait on background daemon threads that may have already been aborted or locks held by other frozen threads.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents