SoFunction
Updated on 2025-04-14

Interpret what the life cycle of a JVM is like

What is the life cycle of a JVM

The life cycle of a JVM refers to the entire process from startup to termination of a JVM instance.

A Java application usually corresponds to a JVM instance (unless multiple JVM instances are created in the same process using techniques such as JNI, but this is not common).

The life cycle phase of JVM

Startup

  • Create a JVM instance:When you usejavaWhen the command runs a Java program, the operating system creates a new process and starts a JVM instance in that process.
  • Loading and initializing:
    • Find and load the JDK:Find the location of JRE (Java Runtime Environment).
    • Create a Bootstrap Class Loader:Loading the core class library (wait).
    • Create an Extension Class Loader and an Application Class Loader:Load the class library and the application's classes separately.
    • loadmain The class where the method is located:Use the application class loader to load the containsmainThe class of the method.
    • Initialization class:Performs static initialization blocks and static variable assignments of the class.
  • Command line parameters: parse incomingjavaParameters of the command.

Run (Execution)

  • implementmain method:JVM callsmainMethod, start executing the Java program.
  • Class loading:During the program running, the class is loaded dynamically as needed.
  • Bytecode execution:The execution engine of the JVM interprets or compiles the execution bytecode.
  • Memory management:JVM allocates and manages memory and performs garbage collection.
  • Thread management:JVM creates and manages threads.
  • Exception handling:Exception that occurs in the JVM handler.

Termination

Normal termination:

  • When the program is completedmainWhen all non-daemon threads have ended, the JVM terminates normally.
  • Can be called by(status)Method explicitly terminates the JVM.statusIt is the exit status code (0 means normal exit, non-0 means abnormal exit).

Exceptional termination:

  • If an uncaught exception occurs in the program and the default uncaught exception handler is not set, the JVM terminates abnormally.
  • Can be passed()Set the default uncaught exception handler.

External Termination:

  • Users can use operating system commands (for example, in LinuxkillCommand) Force the JVM process to terminate.
  • The JVM may receive a termination signal sent by the operating system (for example, SIGTERM).

Shutdown Hooks:

  • Before the JVM terminates, you can register some shutdown hooks to perform some cleaning operations (such as closing a database connection, freeing resources, etc.).
  • Available().addShutdownHook(Thread hook)Method registers hook function.
  • The hook function will be executed in the following cases:
    • The program exits normally.
    • Call()
    • The user interrupts the program (for example, press Ctrl+C).
    • The system is turned off.
  • The order in which the hook function is executed is uncertain.

Summary flow chart

+----------------+
|    start up JVM     |  (java Order)
+----------------+
        |
        V
+----------------+
|  Loading and initializing    |
|  - Find and load JDK |
|  - Create a class loader   |
|  - load main kind   |
|  - 初始化kind      |
+----------------+
        |
        V
+----------------+
|    Run the program     |
|  - implement main method|
|  - kindload       |
|  - 字节码implement    |
|  - Memory management     |
|  - Thread management     |
|  - Exception handling     |
+----------------+
        |
        V
+----------------+
|    termination JVM     |
|  - 正常termination      |
|  - 异常termination      |
|  - 外部termination      |
|  - implement钩子函数   |
+----------------+

Code example (demonstrate hook function)

public class JVMLifecycle {

    public static void main(String[] args) {

        // Register hook function        ().addShutdownHook(new Thread(() -> {
            ("The JVM is about to terminate, perform a cleanup operation...");
            // Perform a cleanup operation here (for example, closing the database connection, freeing resources, etc.)        }));

        ("The program starts executing...");

        // The simulation program runs for a period of time        try {
            (5000);
        } catch (InterruptedException e) {
            ();
        }

        ("The program is completed...");

        // You can choose to explicitly exit (or you can not call exit to let the program end naturally)        // (0);
    }
}

Running results:

The program starts executing...
The program execution is complete...
The JVM is about to terminate, perform a cleanup operation...

Notice:

  • If there is a dead loop or infinite waiting in the program, the JVM may never terminate.
  • Daemon threads (daemon thread) do not prevent JVM termination. When all non-daemon threads are finished, the JVM forces all daemon threads to terminate.
  • The hook function should be as short as possible to avoid time-consuming operations, otherwise the JVM may not terminate properly.
  • Don't call it in hook function(), otherwise it will lead to a dead cycle.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.