JVM Startup and Shutdown: Hooks and Lifecycle

Learn how Java starts and stops, when shutdown hooks run, why finalizers are unreliable, and how to bound cleanup within container timeouts.

published: reading time: 19 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Learn how Java starts and stops, when shutdown hooks run, why finalizers are unreliable, and how to bound cleanup within container timeouts.

JVM Startup and Shutdown: Hooks and Lifecycle

Introduction

Starting a Java process involves the launcher, the virtual machine, class loading, and eventually your application’s entry point. Shutdown follows a separate path: a request to exit starts registered hooks, and the JVM terminates after those hooks finish. Knowing what the runtime guarantees helps you avoid startup assumptions and design cleanup that fits within a service’s shutdown deadline.

This guide focuses on the portable Runtime lifecycle API and uses HotSpot on Unix-like systems for signal examples. JVM initialization details and signal behavior can vary by implementation and operating system.

When NOT to Use

Most applications do not need to change JVM bootstrap settings. Use static initialization only for simple class-level setup, and use the application’s normal lifecycle to start services or close resources. A shutdown hook is appropriate for small, bounded, best-effort cleanup; do not put work there if it must complete exactly once or must survive a crash.

Avoid relying on hook order or assuming application threads have stopped when a hook begins. For background on startup internals, see Runtime Data Areas and Execution Engine.

JVM Bootstrap Process

When you run java -jar myapp.jar, the JVM begins a complex bootstrap sequence before your main method executes.

Bootstrap Sequence

This diagram is a simplified view. The exact internal initialization order is JVM-implementation-specific, and application code registers its own shutdown hooks after it starts running.

sequenceDiagram
    participant OS as Operating System
    participant JVM as JVM Process
    participant Main as Application
    participant Hook as Shutdown Hooks

    OS->>JVM: Start process and launch Java
    JVM->>JVM: Initialize runtime and load entry class
    JVM->>Main: Invoke main()
    Main->>Main: Application runs
    OS-->>JVM: SIGTERM or other exit request
    JVM->>Hook: Start registered hooks concurrently
    Note over Main,Hook: Existing application threads may still be running
    Hook-->>JVM: All hooks terminate
    JVM-->>OS: Terminate process

Step-by-Step Bootstrap

  1. The operating system starts the Java launcher. The launcher locates and starts a JVM implementation for the requested runtime.
  2. The JVM initializes implementation-specific runtime structures. This includes the class-loading system and services needed to execute Java code. Do not treat one internal initialization order as a Java SE guarantee.
  3. The launcher processes options and selects the application entry point. For example, java -jar app.jar reads the JAR’s main-class metadata.
  4. The entry class is loaded and initialized as required. A class’s static initializer runs when that class is initialized; the JVM does not eagerly run every application’s static initializer during bootstrap.
  5. The launcher invokes the application’s main method. Application code can register shutdown hooks through Runtime.addShutdownHook once it is running.

Work That Must Run Before main

Java has no general-purpose application “initialization hook” that automatically runs for every program before main. Static initializers run when their class is initialized, so use them for simple class-level setup rather than external I/O or service startup.

For code that must execute before main, Java agents provide an explicit entry point. A Java agent’s premain method runs before the application’s main method:

java -javaagent:agent.jar -jar app.jar

Native JVMTI agents use -agentlib or -agentpath. -XX:CompileCommand configures compiler behavior; it does not force a method to be compiled before application startup.

Shutdown Hooks

A shutdown hook is an initialized but unstarted Thread registered with Runtime.addShutdownHook. When shutdown begins, the JVM starts registered hooks in an unspecified order. They run concurrently with each other and with daemon or non-daemon threads that were already running.

Hooks are useful for bounded, best-effort cleanup such as stopping an executor or flushing a small amount of buffered data. They are not guaranteed to run after a JVM crash, Runtime.halt, or forced termination such as SIGKILL.

Shutdown Hook Rules

  1. Assume concurrent execution. Hooks have no guaranteed order and may overlap with application threads.
  2. Keep operations bounded. Use timeouts for waits and network operations. The JVM waits for all hooks to terminate, so a hook that never returns can stall shutdown.
  3. Do not call System.exit from a hook. The call blocks indefinitely and prevents that hook from finishing. Runtime.halt bypasses normal cleanup; it is not a routine workaround.
  4. Handle exceptions and shared state. An uncaught exception terminates that hook after its handler runs; other hooks continue. Use normal synchronization for data shared with application threads.
  5. Avoid dependencies on other hooks. A hook must not assume that another library’s hook has already run or that its services are still available.

Shutdown Sequence

The Java SE Runtime API describes shutdown as a short sequence, not a set of finalizer phases.

1. A Shutdown Request Begins

The JVM begins shutdown when the number of live non-daemon threads first reaches zero, when System.exit or Runtime.exit is called, or when an external event such as an operating-system signal requests termination. An explicit exit request does not wait for application threads to finish before starting hooks.

2. Registered Hooks Run Concurrently

The JVM starts registered hooks in an unspecified order and waits for them to terminate. Hooks run at the same time as daemon and non-daemon threads that were already active. If a hook waits forever, shutdown does not finish unless another thread calls Runtime.halt.

3. The JVM Terminates

Once all hooks have terminated, the JVM stops Java threads and terminates. Runtime.halt skips the shutdown sequence entirely. The JVM does not drain a finalizer queue as a normal shutdown phase.

Object.finalize() is deprecated for removal. In JDK 26, finalization is still enabled by default, but can be disabled with --finalization=disabled; either way, finalizers are not a reliable shutdown-cleanup mechanism. Use try-with-resources for deterministic resource cleanup. A Cleaner is a fallback for resources whose owner becomes unreachable, not a replacement for explicit close operations. See JEP 421.

Signal Handling

Signal behavior depends on the operating system and JVM implementation. On HotSpot on Unix-like systems, SIGTERM and SIGINT normally request orderly JVM shutdown, which starts registered hooks. SIGKILL cannot be caught and does not run hooks. On Linux, HotSpot commonly uses SIGQUIT to print diagnostic information such as a thread dump rather than to request shutdown.

# Request graceful shutdown on a Unix-like system
kill -TERM <pid>

# Request HotSpot diagnostics on Linux; this does not request shutdown
kill -QUIT <pid>

Make sure the JVM receives the termination signal. If a container entry point starts a shell wrapper, that wrapper must forward the signal or replace itself with the Java process.

Production Failure Scenarios

Scenario Cause Likely result Response
Hooks are skipped SIGKILL, Runtime.halt, or JVM/process crash Cleanup does not run Make critical work durable during normal operation; use hooks only for best-effort cleanup
Shutdown exceeds container grace period A hook waits indefinitely or cleanup takes too long The orchestrator forcefully terminates the container Bound each wait and align application cleanup budgets with the grace period
Hook never returns Unbounded I/O, lock contention, or a task that ignores interruption JVM remains in shutdown Use timeouts, avoid cross-hook dependencies, and log elapsed cleanup time
main returns but the process stays alive A non-daemon application thread is still running The JVM has not reached natural shutdown Stop the owning service or executor as part of normal application lifecycle
Finalizer-based cleanup is missing Finalization is disabled, delayed, or the process exits first Resource remains open until process termination Use try-with-resources or an explicit close lifecycle

Trade-off Analysis

Choice Consideration
Bounded cleanup vs. waiting for every task A deadline makes termination predictable; tasks that exceed it may be interrupted or abandoned.
Daemon vs. non-daemon threads Non-daemon threads keep a normally running JVM alive. During shutdown, hooks run concurrently with both kinds of existing threads.
Hook cleanup vs. normal lifecycle cleanup Hooks are a final opportunity to stop services, but normal application code should close resources before shutdown whenever possible.
Orchestrator grace period vs. cleanup budget The grace period must cover any pre-stop delay, application cleanup, and a margin before forced termination.

Failure Scenarios Deep Dive

Static Initialization Fails During Startup

If a static initializer throws an exception, the JVM marks that class as having failed initialization. The first active use reports an ExceptionInInitializerError when the thrown value is not already an Error; later attempts to use that class typically fail with NoClassDefFoundError.

Circular references between static initializers do not automatically produce a StackOverflowError. A class can observe default-valued static fields while initialization is in progress, which can lead to incorrect state. Keep static initialization simple and move dependency resolution, I/O, and service startup into explicit methods or constructors.

The Process Stays Alive After main Returns

Returning from main does not start shutdown while a non-daemon thread is still alive. A thread pool, scheduled worker, or server loop may keep the process running. Add an explicit application stop path that stops accepting work, shuts down owned executors, and waits with a deadline. Do not mark threads as daemon merely to hide a lifecycle bug when they own work that must finish.

A termination signal is a separate shutdown trigger: when the JVM receives one that requests shutdown, it begins running hooks even if application threads are still alive. Those threads run concurrently with the hooks and may hold locks or services the hooks need, so coordinate shutdown through the application’s normal lifecycle where possible.

A Flight Recording Is Missing After Termination

A JFR recording is not automatically dumped on every crash or forced termination. In HotSpot JDK 26, dumponexit is disabled by default for a recording; configure it or use jcmd to dump a recording while the JVM is still available. A crash or SIGKILL can prevent a final dump from being written. Leave enough disk space for recordings and verify the recording configuration before relying on it for incident analysis.

Bounded SIGTERM Handling

This HotSpot example stops accepting work, asks an executor to finish its queued tasks, and waits for a fixed budget. If that budget expires, it interrupts remaining tasks and waits for a shorter final period. shutdownNow() is best effort; a task that ignores interruption can still outlive the wait.

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

public final class GracefulShutdown {
    private static final CountDownLatch STOPPED = new CountDownLatch(1);
    private static final ExecutorService WORKERS =
        Executors.newSingleThreadExecutor();

    public static void main(String[] args) throws InterruptedException {
        Runtime.getRuntime().addShutdownHook(
            new Thread(GracefulShutdown::stop, "shutdown-hook")
        );
        STOPPED.await();
    }

    private static void stop() {
        // Stop accepting requests before draining the service's own work.
        WORKERS.shutdown();
        try {
            if (!WORKERS.awaitTermination(20, TimeUnit.SECONDS)) {
                WORKERS.shutdownNow();
                if (!WORKERS.awaitTermination(5, TimeUnit.SECONDS)) {
                    System.err.println("Workers did not stop within the cleanup budget");
                }
            }
        } catch (InterruptedException e) {
            WORKERS.shutdownNow();
            Thread.currentThread().interrupt();
        } finally {
            STOPPED.countDown();
        }
    }
}

The waits above allow up to 25 seconds for executor cleanup. They are example limits, not Java defaults. For Kubernetes, the following illustrative grace period leaves a short margin after those waits:

spec:
  terminationGracePeriodSeconds: 30

Set the grace period to cover any preStop work, the application’s cleanup budget, and a margin. Kubernetes’ grace-period countdown includes preStop; a long pre-stop delay reduces the time left for Java hooks. Ensure the Java process receives SIGTERM before the grace period expires, or Kubernetes can force termination with SIGKILL.

Observability Checklist

  • Log when shutdown begins and when each cleanup step completes.
  • Record elapsed time for hook work and compare it with the configured grace period.
  • Track graceful exits separately from forced termination and JVM crashes.
  • Keep enough disk space for crash logs and configured JFR recordings.
  • Confirm the process receives SIGTERM and that the container exits before its deadline.
  • Make critical state durable before shutdown rather than relying on a hook to save it.

Security Notes

A shutdown hook runs as code inside the JVM process and has the same process-level access as the application. Restrict who can deploy code or change launch arguments. Protect process signals and diagnostic access, and do not place secrets in hook logs or crash artifacts.

Hooks run concurrently with threads that were already active. If cleanup reads or changes shared state, use the same synchronization and lifecycle controls as the rest of the application.

Common Pitfalls / Anti-Patterns

Registering shutdown hooks from library code. Libraries can compete with application hooks and may rely on services that are already stopping. Prefer an explicit close or stop method owned by the application.

Assuming shutdown is always graceful. SIGKILL, Runtime.halt, and process crashes bypass hooks. Keep important state durable during normal operation.

Using hooks for critical cleanup. Hooks are a final best-effort opportunity. They cannot guarantee that a database transaction, file write, or remote request completes.

Waiting without a deadline. The JVM waits for hooks to terminate. Bound network, executor, and lock waits so an orchestrator has time to stop the process.

Assuming application threads have stopped before hooks begin. Hooks run concurrently with threads that were alive when shutdown started. Coordinate the application’s normal stop sequence and account for shared locks and services.

Quick Recap Checklist

  • JVM startup internals vary by implementation; do not rely on a universal internal ordering.
  • Static initializers run when their classes are initialized; they are not general-purpose startup hooks.
  • Shutdown begins when non-daemon threads reach zero, an exit method is called, or an external event requests termination.
  • Hooks run concurrently with one another and with threads that were already running.
  • System.exit from a hook blocks that hook; Runtime.halt skips the shutdown sequence.
  • SIGKILL and process crashes do not provide a cleanup callback.
  • Finalization is deprecated for removal and is not a shutdown phase or reliable cleanup mechanism.
  • Bound cleanup time and align it with the container or service-manager grace period.

Interview Questions

1. What is the order of events during JVM shutdown?

In Java SE, shutdown starts when the last live non-daemon thread ends, System.exit/Runtime.exit is called, or an external event requests termination. Registered hooks start in an unspecified order and run concurrently with one another and with threads that were already active. The JVM terminates after all hooks finish. Finalization is not a shutdown phase, and a crash or forced termination may prevent hooks from running.

2. What happens if a shutdown hook calls System.exit()?

System.exit called from a shutdown hook blocks indefinitely, preventing that hook from terminating and the shutdown sequence from finishing. Do not call it from a hook. Runtime.halt terminates immediately and bypasses remaining cleanup; it is not a safe workaround.

3. How do you implement graceful shutdown of an ExecutorService?

Call shutdown() to reject new tasks, wait with awaitTermination(timeout, unit), then call shutdownNow() if the deadline expires. Optionally wait for a shorter final period. Handle InterruptedException and remember that interruption is best effort: tasks that ignore it may not stop before the JVM terminates.

4. What signals does the JVM handle and how?

Signal mappings depend on the operating system and JVM. On HotSpot on Unix-like systems, SIGTERM and SIGINT normally request orderly shutdown. On Linux, SIGQUIT commonly requests diagnostic output such as a thread dump. SIGKILL cannot be caught, so hooks do not run. A JVM crash also does not guarantee hook completion.

5. Why should you avoid using Object.finalize() and what should you use instead?

Finalization is deprecated for removal because it is unpredictable and can delay cleanup; it may also be disabled. In JDK 26 it remains enabled by default unless disabled with --finalization=disabled. Use try-with-resources or an explicit close() lifecycle for deterministic cleanup. A Cleaner is only a fallback when an object becomes unreachable, not a replacement for closing resources.

6. What happens during the JVM bootstrap phase before the main method executes?

The launcher starts a JVM, processes options, loads the selected entry class, and invokes its main method. The VM initializes implementation-specific runtime structures along the way, but Java does not guarantee one universal internal order. A class’s static initializer runs when that class is initialized, not as a blanket pass over all application classes.

7. What is the difference between Runtime.halt() and System.exit() in shutdown hooks?

System.exit() initiates or joins the normal shutdown sequence, which runs registered hooks. If a hook calls it, that call blocks indefinitely. Runtime.halt() terminates immediately without waiting for the shutdown sequence or hooks to finish.

8. Why might a shutdown hook run multiple times or not at all?

A registered hook thread is run at most once in a JVM shutdown sequence. The same Thread object cannot be registered twice; a second registration is rejected. Hooks may not run if shutdown is bypassed with Runtime.halt, the process is killed with SIGKILL, or the JVM or operating system crashes.

9. How does the module system affect class loading order during JVM startup?

The module system resolves module readability and accessibility; it does not impose a complete order in which every class must be loaded. Classes are loaded as execution requires them. The bootstrap, platform, and application loaders have defined roles in the runtime, while module resolution is a separate step.

10. How should you handle a flag that is missing from current JDK documentation?

That is a historical HotSpot option and should not be copied into a current launch command. Option support and behavior vary by JDK release. Check the target release’s Java launcher reference and inspect the deployed process rather than relying on an old flag description.

11. How can code run before the application main method?

Java does not define a general application initialization-hook API that automatically runs before main. Java agents expose a premain entry point before the application main method. Shutdown hooks are threads registered with Runtime.addShutdownHook and run when the JVM begins orderly shutdown.

12. How does Flight Recorder integrate with JVM shutdown?

JFR is not a Java shutdown hook. A recording is dumped at JVM shutdown only when configured to do so; in HotSpot JDK 26, dumponexit is disabled by default. A process crash or forced termination can prevent a final dump, so configure and verify the recording before relying on it.

13. What are the main steps of JVM shutdown?

Java SE does not define five shutdown phases. The useful model is: a shutdown request begins, registered hooks run concurrently, then the JVM terminates after the hooks finish. Finalizers are not drained as part of this sequence.

14. What happens when a static initializer causes an exception during class loading?

If a static initializer throws a non-Error exception, the first active use reports it wrapped in ExceptionInInitializerError. If initialization fails, later active uses generally fail with NoClassDefFoundError. The original cause is available from the initialization error.

15. Why should shutdown hooks be fast and non-blocking?

The JVM waits for every hook to terminate. A hook that blocks forever can stall shutdown, and a container may force-kill the process when its grace period expires. Bounded waits are appropriate; unbounded network calls, lock waits, or computations are not.

16. Which shutdown details are implementation-specific?

Internal VM threads and shutdown coordination are implementation details, not Java SE lifecycle guarantees. Application code should rely on the documented behavior of Runtime: hooks start at shutdown, run concurrently, and must terminate before normal JVM termination proceeds.

17. What does class verification guarantee during startup?

Class-file verification checks that loaded bytecode satisfies JVM structural and type-safety rules before execution. It is not a sandbox and does not guarantee that code cannot exhaust resources or crash the process. Class initialization then runs the relevant static initializer when required.

18. What happens if you register the same shutdown hook twice?

Runtime.addShutdownHook accepts a Thread, not a Runnable. Registering the same thread object twice throws IllegalArgumentException; create a distinct thread only when you truly need a separate hook. Hooks should still tolerate repeated cleanup requests from the application’s normal stop path.

19. How can you trace class initialization on HotSpot JDK 26?

For HotSpot JDK 26, the legacy -XX:+TraceClassInitialization option maps to unified logging: -Xlog:class+init=info. Use it for a focused diagnostic run, since class initialization logs can be verbose. Confirm the mapping in the target JDK’s launcher reference.

20. What is the relationship between daemon threads and shutdown hooks?

Daemon threads do not keep a normally running JVM alive once all non-daemon threads have ended. When shutdown starts for another reason, hooks run concurrently with daemon and non-daemon threads that were already active. After hooks finish, the JVM terminates its remaining threads without waiting for their cleanup code.

Further Reading

Conclusion

JVM shutdown hooks run when orderly shutdown begins, alongside threads that may still be using application services. Keep hook work small, synchronized where needed, and bounded by explicit deadlines. A process crash, Runtime.halt, or SIGKILL can skip hooks entirely, so complete critical cleanup and persist important state during normal operation.

For containers, choose an application cleanup budget that fits inside the orchestrator’s grace period, including any pre-stop delay and a margin. Finalization is deprecated for removal and is not part of the shutdown sequence; use explicit resource management instead.

Category

Related Posts

GraalVM Native Image

Measure GraalVM Native Image startup, memory, throughput, and build costs while learning its reachability metadata requirements.

#graalvm #native-image #aot

React Effects with useEffect: Synchronizing Systems

Learn when React effects are needed, how dependencies control resynchronization, and how cleanup prevents leaked timers and subscriptions.

#react #typescript #useeffect

React State with useState and TypeScript

Learn how useState snapshots work, how TypeScript infers state types, and how to update objects and arrays immutably in React components.

#react #typescript #state