Signals and graceful shutdown
suggest changeA 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:
- stops accepting new work
- finishes or saves the work it already has
- releases resources: flushes files, closes database connections, removes temporary files
- 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:
- the last non-daemon thread finishes (for example
mainreturns) exitProcess(code)orSystem.exit(code)is called- the process receives
SIGINT,SIGTERMorSIGHUP
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:
- All hooks start at the same time and run concurrently, in no particular order. If cleanup steps depend on each other, register one hook that runs them in sequence (see below).
- Keep them short. The JVM waits for every hook to finish, and the process manager is counting down to
SIGKILL. - Don't call
exitProcess()in a hook. Shutdown is already in progress andexitblocks forever, so the JVM hangs.Runtime.getRuntime().halt(code)does work, but it stops immediately, skipping hooks that haven't finished. - You can't add or remove hooks once shutdown has started:
addShutdownHookthrowsIllegalStateException. removeShutdownHook(thread)unregisters a hook, for example when a component is closed early.
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:
- Ktor registers a shutdown hook in
embeddedServer(...).start(). You can tune it withshutdownGracePeriodandshutdownTimeout(in milliseconds) in the engine configuration, orktor.deployment.shutdownGracePeriodandktor.deployment.shutdownTimeoutinapplication.conf. Run your own cleanup withmonitor.subscribe(ApplicationStopping) { ... }inside the application module. - Spring Boot waits for active requests when
server.shutdown=graceful(the default since 3.4), up tospring.lifecycle.timeout-per-shutdown-phase.
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:
- Each signal is delivered by a new thread (named like
SIGHUP handler), so the handler must be thread-safe. That's whyconfigis anAtomicReference. - It replaces the JVM's handler. Handling
SIGHUPthis way meansSIGHUPno longer shuts the JVM down. The old handler is returned, so you can call it yourself to chain. - Signal names are given without the
SIGprefix. Signals the JVM uses internally, likeQUIT, throwIllegalArgumentException, as do signals the OS doesn't have. On Windows onlyINT,TERM,BREAKand a few error signals exist;Signal("HUP")fails there. SIGUSR1is a good choice for custom actions like "dump statistics" or "rotate logs".SIGUSR2is used by HotSpot itself on Linux.
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
- Logging may already be shut down. Log4j 2 registers its own shutdown hook, and since hooks run in parallel your final log messages can be lost. Disable Log4j's hook (
log4j2.shutdownHookEnabled=false) and stop logging yourself as the last step of your hook. Logback needs<shutdownHook/>in its configuration to flush asynchronous appenders. See Logging. - Daemon threads are just stopped. They don't block shutdown, but their
finallyblocks don't run either. Don't do important writes on daemon threads without a hook that waits for them. - A deadlock in a hook hangs the process until
SIGKILL. Always use timeouts (await(timeout),withTimeoutOrNull,awaitTermination) when waiting in a hook. exitProcess()inside a hook, or inside code that a hook waits for, hangs forever.- A hook that throws prints the stack trace and ends that hook, but other hooks still run and the JVM still exits. Catch exceptions per cleanup step so one failure doesn't skip the rest.
- Out-of-memory kills skip everything. When the Linux OOM killer or a container memory limit kills the JVM, it gets
SIGKILL. Write important state as you go, not only on shutdown. -Xrs(reduce signal usage) stops the JVM from installing its own signal handlers, so shutdown hooks don't run onSIGINT/SIGTERM. Make sure it's not inJAVA_OPTS.