Signals and graceful shutdown

suggest change

A long-running program like a server, worker or daemon doesn't get to decide when it ends. The user presses Ctrl+C, docker stop or Kubernetes sends SIGTERM, or a deploy script runs kill. A graceful shutdown means that when this happens, the program:

  1. stops accepting new work
  2. finishes or saves the work it already has
  3. releases resources: flushes files, closes database connections, removes temporary files
  4. exits within a time limit

Kotlin on the JVM does this with shutdown hooks. For finer control there is the unofficial sun.misc.Signal API.

Signals the JVM cares about

Signal Sent by Default JVM behavior
SIGINT (2) Ctrl+C in a terminal runs shutdown hooks, exits with 130
SIGTERM (15) kill <pid>, docker stop, Kubernetes, systemd runs shutdown hooks, exits with 143
SIGHUP (1) terminal closed runs shutdown hooks, exits with 129
SIGQUIT (3) Ctrl+\ prints a thread dump, keeps running
SIGKILL (9) kill -9, after a grace period runs out the process dies instantly, nothing runs

The exit code after a signal is 128 plus the signal number. SIGKILL can't be caught by any program, so a graceful shutdown must finish before the sender loses patience and sends it. docker stop waits 10 seconds by default and Kubernetes waits 30 (terminationGracePeriodSeconds).

On Windows there are no POSIX signals, but Ctrl+C and Ctrl+Break in a console act like SIGINT and the JVM runs shutdown hooks. taskkill /F is the equivalent of kill -9.

The problem: finally doesn't run

You might expect finally to handle cleanup. It doesn't when the process is stopped by a signal:

fun main() {
    try {
        while (true) {
            println("working...")
            Thread.sleep(1000)
        }
    } finally {
        println("cleanup") // never printed on Ctrl+C
    }
}
working...
working...
^C

When the JVM gets SIGTERM or SIGINT it doesn't interrupt or unwind the main thread. It runs the shutdown hooks and then halts, stopping every remaining thread on the spot. finally blocks, use { } and coroutine finally blocks in those threads never execute.

Shutdown hooks

A shutdown hook is an unstarted Thread registered with Runtime.addShutdownHook. Kotlin's thread(start = false) { } from kotlin.concurrent creates one neatly:

import kotlin.concurrent.thread

fun main() {
    Runtime.getRuntime().addShutdownHook(thread(start = false, name = "shutdown-hook") {
        println("shutdown hook: cleaning up")
    })

    println("working... (pid ${ProcessHandle.current().pid()})")
    Thread.sleep(60_000)
    println("finished normally")
}

Pressing Ctrl+C:

working... (pid 41822)
^Cshutdown hook: cleaning up
$ echo $?
130

Running kill 41822 from another terminal gives the same output and exit code 143.

Shutdown hooks run when the JVM shuts down in an orderly way:

They do not run on SIGKILL, Runtime.halt(), a JVM crash, or when the OS kills the process for using too much memory.

Rules for hooks:

Stopping the main loop and waiting for it

A hook that just cleans up runs concurrently with your still-running main thread. The hook may close a database connection while the main loop is in the middle of using it. The usual fix is to make the hook ask the main loop to stop and then wait for it to finish:

import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.concurrent.thread

val running = AtomicBoolean(true)
val stopped = CountDownLatch(1)

fun main() {
    Runtime.getRuntime().addShutdownHook(thread(start = false, name = "shutdown-hook") {
        println("shutdown: asking worker to stop")
        running.set(false)
        if (stopped.await(10, TimeUnit.SECONDS)) {
            println("shutdown: worker stopped cleanly")
        } else {
            println("shutdown: worker didn't stop in 10s, exiting anyway")
        }
    })

    try {
        var n = 0
        while (running.get()) {
            n++
            println("processing item $n")
            Thread.sleep(1000)
        }
        println("worker: saving progress at item $n")
    } finally {
        stopped.countDown()
    }
}
processing item 1
processing item 2
processing item 3
^Cshutdown: asking worker to stop
worker: saving progress at item 3
shutdown: worker stopped cleanly

The worker checks the flag between items, so it never stops halfway through one. The timeout makes sure a stuck worker can't block shutdown forever. If the loop ends on its own, stopped has already been counted down by the time the hook runs, so the hook returns at once.

For a worker that blocks for a long time (in Thread.sleep, BlockingQueue.take() or similar), call workerThread.interrupt() from the hook too, so it wakes up and sees the flag.

One hook, ordered cleanup

Real programs have several resources and they must close in the reverse order they were opened: stop the HTTP server before closing the database pool it uses, and flush logs last. Since separate hooks run in parallel, use a single hook with a stack of actions:

import kotlin.concurrent.thread

object Shutdown {
    private val actions = ArrayDeque<Pair<String, () -> Unit>>()

    init {
        Runtime.getRuntime().addShutdownHook(thread(start = false, name = "shutdown") { runAll() })
    }

    @Synchronized
    fun register(name: String, action: () -> Unit) {
        actions.addLast(name to action)
    }

    @Synchronized
    private fun runAll() {
        while (actions.isNotEmpty()) {
            val (name, action) = actions.removeLast() // last registered, first closed
            try {
                println("closing $name")
                action()
            } catch (e: Exception) {
                println("error closing $name: $e") // keep going, close the rest
            }
        }
    }
}

fun main() {
    Shutdown.register("database pool") { /* pool.close() */ }
    Shutdown.register("cache") { error("disk full") }
    Shutdown.register("http server") { /* server.stop(5) */ }
    println("running")
}
running
closing http server
closing cache
error closing cache: java.lang.IllegalStateException: disk full
closing database pool

There's no signal here: main returned, the JVM began an orderly shutdown and ran the hook. One failing step doesn't prevent the others from running.

Coroutines

With coroutines, graceful shutdown is cancellation: the hook cancels the application's job and waits for it to finish. Coroutine finally blocks run as part of cancellation, so cleanup goes there:

import kotlinx.coroutines.*
import kotlin.concurrent.thread

fun main() = runBlocking {
    val app = launch(Dispatchers.Default) {
        try {
            while (true) {
                println("tick")
                delay(1000)
            }
        } finally {
            // the coroutine is cancelled; suspending calls need NonCancellable
            withContext(NonCancellable) {
                println("saving state...")
                delay(300) // e.g. a suspending write to the database
                println("state saved")
            }
        }
    }

    Runtime.getRuntime().addShutdownHook(thread(start = false, name = "shutdown-hook") {
        println("shutdown requested")
        runBlocking {
            val done = withTimeoutOrNull(5_000) { app.cancelAndJoin() }
            if (done == null) println("app didn't stop within 5s")
        }
    })

    app.join()
}
tick
tick
tick
^Cshutdown requested
saving state...
state saved

Calling runBlocking inside the hook is fine: the hook is an ordinary thread and it has to block anyway, because the JVM halts as soon as the hook returns.

For an application with many coroutines, create a top-level CoroutineScope(SupervisorJob() + Dispatchers.Default), launch everything in it, and in the hook call scope.coroutineContext.job.cancelAndJoin(). Every child is cancelled and the hook waits for all of them.

Thread pools

An ExecutorService has its own two-step shutdown: shutdown() stops it from accepting new tasks and lets queued ones run, shutdownNow() interrupts running tasks and drops queued ones:

import java.util.concurrent.ExecutorService
import java.util.concurrent.TimeUnit

fun ExecutorService.shutdownGracefully(timeoutSeconds: Long) {
    shutdown()
    if (!awaitTermination(timeoutSeconds, TimeUnit.SECONDS)) {
        val dropped = shutdownNow()
        println("forced shutdown, ${dropped.size} tasks never started")
        awaitTermination(timeoutSeconds, TimeUnit.SECONDS)
    }
}

Since Java 19 ExecutorService is AutoCloseable. Its close() calls shutdown() and waits for all tasks with no time limit, which is handy with use { } but not what you want in a shutdown hook with a deadline.

A graceful HTTP server

The JDK's built-in com.sun.net.httpserver.HttpServer shows the pattern with no dependencies. stop(delay) closes the listening socket so no new connections arrive, then waits up to delay seconds for in-flight requests:

import com.sun.net.httpserver.HttpServer
import java.net.InetSocketAddress
import java.util.concurrent.Executors
import kotlin.concurrent.thread

fun main() {
    val executor = Executors.newVirtualThreadPerTaskExecutor()
    val server = HttpServer.create(InetSocketAddress(8080), 0)
    server.executor = executor

    server.createContext("/") { exchange ->
        Thread.sleep(3000) // a slow request
        val body = "done\n".toByteArray()
        exchange.sendResponseHeaders(200, body.size.toLong())
        exchange.responseBody.use { it.write(body) }
    }

    Runtime.getRuntime().addShutdownHook(thread(start = false, name = "shutdown-hook") {
        println("stopping: refusing new connections, waiting for requests in progress")
        server.stop(10)
        executor.close()
        println("stopped")
    })

    server.start()
    println("listening on http://localhost:8080 (pid ${ProcessHandle.current().pid()})")
}

Start a request with curl localhost:8080 and press Ctrl+C in the server's terminal while it's running. The server waits and curl still prints done:

listening on http://localhost:8080 (pid 52310)
^Cstopping: refusing new connections, waiting for requests in progress
stopped

Frameworks do this for you:

Behind a load balancer, also mark the instance as not ready (fail the readiness check) before stopping, so traffic is routed elsewhere first. In Kubernetes a short preStop sleep gives the endpoints time to update.

Handling signals directly with sun.misc.Signal

Shutdown hooks can't tell which signal arrived, and they only fire on shutdown. To react to a signal without exiting, for example to reload configuration on SIGHUP, use sun.misc.Signal. It's not a public API, but it lives in the jdk.unsupported module, which is available without any flags and is used by many libraries, so it's not going away soon:

import sun.misc.Signal
import java.util.concurrent.atomic.AtomicReference

fun loadConfig(): Map<String, String> = mapOf("loadedAt" to java.time.LocalTime.now().toString())

val config = AtomicReference(loadConfig())

fun main() {
    Signal.handle(Signal("HUP")) { sig ->
        println("got SIG${sig.name} (${sig.number}), reloading config")
        config.set(loadConfig())
    }

    println("pid ${ProcessHandle.current().pid()}")
    while (true) {
        println("config: ${config.get()}")
        Thread.sleep(5000)
    }
}
$ kill -HUP 60117      # from another terminal
pid 60117
config: {loadedAt=10:15:02.114273581}
got SIGHUP (1), reloading config
config: {loadedAt=10:15:06.870561204}

Things to know about Signal.handle:

Press Ctrl+C twice to force quit

Many CLI tools shut down gracefully on the first Ctrl+C and quit immediately on the second. With Signal.handle you can do the same:

import sun.misc.Signal
import java.util.concurrent.atomic.AtomicInteger
import kotlin.concurrent.thread
import kotlin.system.exitProcess

fun main() {
    val presses = AtomicInteger()
    Signal.handle(Signal("INT")) {
        if (presses.incrementAndGet() == 1) {
            println("shutting down gracefully, press Ctrl+C again to force")
            exitProcess(130) // starts the shutdown and runs the hooks
        } else {
            println("forced exit")
            Runtime.getRuntime().halt(130)
        }
    }

    Runtime.getRuntime().addShutdownHook(thread(start = false) {
        println("cleanup started (takes 10s)")
        Thread.sleep(10_000) // slow cleanup
        println("cleanup finished")
    })

    while (true) Thread.sleep(1000)
}
^Cshutting down gracefully, press Ctrl+C again to force
cleanup started (takes 10s)
^Cforced exit

exitProcess blocks the first handler thread while the hooks run, but the second Ctrl+C is delivered on a new thread, which can still halt.

Containers and process managers

The JVM can only shut down gracefully if the signal reaches it.

In a Dockerfile use the exec form of ENTRYPOINT or CMD, so java runs as PID 1 and receives SIGTERM directly:

FROM eclipse-temurin:25-jre
COPY build/libs/app-all.jar /app/app.jar
# good: java is PID 1
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
# bad: /bin/sh is PID 1 and may not pass SIGTERM on, so docker stop
# waits 10s and then kills java with SIGKILL
# ENTRYPOINT java -jar /app/app.jar

If you need a wrapper shell script, end it with exec java ... so the JVM replaces the shell. The start scripts generated by Gradle's application plugin already do this. docker run --init adds a tiny init process that forwards signals and reaps zombie processes.

Make the grace period longer than your shutdown timeout: docker stop -t 30, terminationGracePeriodSeconds in Kubernetes, TimeoutStopSec= in a systemd unit. systemd sends SIGTERM by default, so a JVM service needs nothing special.

See Building and distributing programs for building the JAR and container image.

Testing shutdown

Run the program from a JAR, not through ./gradlew run: Gradle sits between the terminal and your program and doesn't always pass signals on the way a real deployment does.

$ java -jar build/libs/app-all.jar &
[1] 71234
$ kill -TERM 71234
$ wait 71234; echo "exit code $?"
exit code 143

You can also test the shutdown path in-process: put the cleanup logic in a regular function, call it from the hook, and call it directly from a unit test.

Gotchas

Feedback about page:

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



Table Of Contents