Understanding the Java Virtual Machine (JVM) Internals
The JVM enables Java’s "write once, run anywhere" capability by executing bytecode through four main components: 1. The Class Loader Subsystem loads, links, and initializes .class files using bootstrap, extension, and application class loaders, ensuring secure and lazy class loading; 2. Runtime Data Areas include method area, heap (divided into young and old generations), thread-private stacks, PC registers, and native method stacks, which together manage memory and execution state; 3. The Execution Engine interprets or compiles bytecode using an interpreter and Just-In-Time (JIT) compiler with tiered compilation for performance, while the garbage collector reclaims unused heap memory using algorithms like G1 GC or ZGC; 4. The Native Method Interface (JNI) allows interaction with native libraries in C/C , enabling access to platform-specific features but requiring caution to avoid crashes or security risks—understanding these components helps developers diagnose performance issues, tune memory settings, interpret GC logs, and avoid memory leaks or deadlocks, ultimately leading to more efficient and robust Java applications.
The Java Virtual Machine (JVM) is the engine that drives Java applications, enabling the "write once, run anywhere" promise. While most developers are familiar with writing Java code, understanding what happens under the hood—inside the JVM—can help you write more efficient, robust, and scalable applications. Let’s break down the core components and processes that make the JVM work.

1. Class Loader Subsystem
The JVM doesn’t execute Java source code directly. It runs bytecode (.class
files), and the first step in this process is loading, linking, and optionally initializing classes.
-
Loading: The class loader subsystem loads bytecode into memory. There are three built-in class loaders:
-
Bootstrap Class Loader: Loads core Java libraries (e.g.,
rt.jar
). - Extension Class Loader: Loads classes from the extension directories.
- Application (System) Class Loader: Loads classes from the application’s classpath.
-
Bootstrap Class Loader: Loads core Java libraries (e.g.,
Classes are loaded lazily—only when they’re first needed.

Linking: After loading, the class is verified (ensures bytecode is valid and safe), prepared (static fields are allocated memory), and optionally resolved (symbolic references are replaced with direct references).
-
Initialization: Static initializers and static variable assignments are executed in the order they appear in the source code.
This process ensures security and consistency before any code runs.
2. Runtime Data Areas
The JVM organizes memory into several runtime areas, each serving a specific purpose:
Method Area: Stores class structures, field and method data, constant pool, and code for methods. It’s shared among all threads.
-
Heap: The runtime data area where objects and arrays are allocated. It’s also shared across threads and is the primary target of garbage collection.
- Young Generation (Eden, Survivor spaces)
- Old (Tenured) Generation
-
Stack (Java Virtual Machine Stack): Created per thread. Each method invocation creates a stack frame containing:
- Local variables
- Operand stack
- Frame data (e.g., references to runtime constant pool)
Stack memory is private to the thread and reclaimed automatically when methods return.
PC (Program Counter) Register: Holds the address of the current instruction being executed in a thread. Very lightweight.
Native Method Stack: Used for native (non-Java) methods, such as those written in C/C .
Understanding these areas helps explain memory-related errors like OutOfMemoryError
or StackOverflowError
.
3. Execution Engine
This is where bytecode gets executed. The engine interprets or compiles bytecode into native machine instructions.
Interpreter: Reads bytecode line by line and executes it. Fast to start but slower in execution.
-
Just-In-Time (JIT) Compiler: To overcome the slowness of interpretation, the JIT compiler identifies "hot" methods (frequently executed) and compiles them into native code for faster execution.
- Tiered compilation (used in HotSpot JVM) combines both interpreter and JIT at different levels for optimal performance.
-
Garbage Collector (GC): Automatically reclaims memory by removing unreachable objects from the heap. Different GC algorithms exist:
- Serial GC (simple, for small apps)
- Parallel GC (throughput-focused)
- G1 GC (for large heaps, low pause times)
- ZGC / Shenandoah (ultra-low pause, scalable)
The GC runs on its own schedule and is crucial for preventing memory leaks.
4. Native Method Interface (JNI) and Libraries
The JVM can interact with native code via the JNI. This allows Java applications to call C/C libraries and vice versa. It’s useful for performance-critical operations or accessing platform-specific features (e.g., file system, hardware).
However, misuse of JNI can lead to crashes or security issues since it bypasses JVM safety checks.
Understanding JVM internals isn’t just academic—it helps you:
- Diagnose performance bottlenecks
- Tune memory settings (e.g.,
-Xmx
,-Xms
,-XX:MaxGCPauseMillis
) - Interpret GC logs
- Avoid common pitfalls like memory leaks or thread deadlocks
You don’t need to memorize every detail, but knowing how the JVM manages memory, loads classes, and executes code gives you a real edge when debugging or optimizing Java applications.
Basically, the JVM is a sophisticated runtime system that balances performance, memory management, and portability—and peeking under the hood makes you a better Java developer.
The above is the detailed content of Understanding the Java Virtual Machine (JVM) Internals. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

First,checkiftheFnkeysettingisinterferingbytryingboththevolumekeyaloneandFn volumekey,thentoggleFnLockwithFn Escifavailable.2.EnterBIOS/UEFIduringbootandenablefunctionkeysordisableHotkeyModetoensurevolumekeysarerecognized.3.Updateorreinstallaudiodriv

TestthePDFinanotherapptodetermineiftheissueiswiththefileorEdge.2.Enablethebuilt-inPDFviewerbyturningoff"AlwaysopenPDFfilesexternally"and"DownloadPDFfiles"inEdgesettings.3.Clearbrowsingdataincludingcookiesandcachedfilestoresolveren

Python's logging module can write logs to files through FileHandler. First, call the basicConfig configuration file processor and format, such as setting the level to INFO, using FileHandler to write app.log; secondly, add StreamHandler to achieve output to the console at the same time; Advanced scenarios can use TimedRotatingFileHandler to divide logs by time, for example, setting when='midnight' to generate new files every day and keep 7 days of backup, and make sure that the log directory exists; it is recommended to use getLogger(__name__) to create named loggers, and produce

Using String.join() (Java8) is the easiest recommended method for connecting string arrays, just specify the separator directly; 2. For old versions of Java or when more control is needed, you can use StringBuilder to manually traverse and splice; 3. StringJoiner is suitable for scenarios that require more flexible formats such as prefixes and suffixes; 4. Using Arrays.stream() combined with Collectors.joining() is suitable for filtering or converting the array before joining; To sum up, if Java8 and above is used, the String.join() method should be preferred in most cases, which is concise and easy to read, but for complex logic, it is recommended.

Using PandasStyling in JupyterNotebook can achieve the beautiful display of DataFrame. 1. Use highlight_max and highlight_min to highlight the maximum value (green) and minimum value (red) of each column; 2. Add gradient background color (such as Blues or Reds) to the numeric column through background_gradient to visually display the data size; 3. Custom function color_score combined with applymap to set text colors for different fractional intervals (≥90 green, 80~89 orange, 60~79 red,

Computed has a cache, and multiple accesses are not recalculated when the dependency remains unchanged, while methods are executed every time they are called; 2.computed is suitable for calculations based on responsive data. Methods are suitable for scenarios where parameters are required or frequent calls but the result does not depend on responsive data; 3.computed supports getters and setters, which can realize two-way synchronization of data, but methods are not supported; 4. Summary: Use computed first to improve performance, and use methods when passing parameters, performing operations or avoiding cache, following the principle of "if you can use computed, you don't use methods".

Run the child process using the os/exec package, create the command through exec.Command but not execute it immediately; 2. Run the command with .Output() and catch stdout. If the exit code is non-zero, return exec.ExitError; 3. Use .Start() to start the process without blocking, combine with .StdoutPipe() to stream output in real time; 4. Enter data into the process through .StdinPipe(), and after writing, you need to close the pipeline and call .Wait() to wait for the end; 5. Exec.ExitError must be processed to get the exit code and stderr of the failed command to avoid zombie processes.
