Comprehensive Overview of Java JVM Runtime Data Areas, Memory Model, Garbage Collection, and Class Loading
This article provides a detailed explanation of the Java Virtual Machine's runtime memory regions, the Java Memory Model, garbage collection mechanisms, heap layout, HotSpot VM internals, class loading process, and performance tuning parameters, offering a solid foundation for Java developers and architects.
Java Runtime Data Areas
The JVM divides the memory it manages into several distinct runtime data areas, each with its own purpose and lifecycle. Some areas exist for the lifetime of the JVM process, while others are created and destroyed with individual threads.
Java虚拟机在执行Java程序的过程中会将其管理的内存划分为若干个不同的数据区域,这些区域有各自的用途、创建和销毁的时间,有些区域随虚拟机进程的启动而存在,有些区域则是依赖用户线程的启动和结束来建立和销毁。Java虚拟机所管理的内存包括以下几个运行时数据区域,如图:1. Program Counter (PC) Register: points to the current bytecode instruction of each thread; thread‑private.
2. Java Virtual Machine Stack: stores stack frames for method execution. Each frame contains a local variable table, operand stack, dynamic linking information, and a return value.
3. Native Method Stack: memory model for invoking native (C/C++) methods; also thread‑private.
4. Method Area: stores loaded class metadata, constants, static variables, and JIT‑compiled code; shared among threads. It includes the runtime constant pool.
A、是方法区的一部分
B、存放编译期生成的各种字面量和符号引用
C、Class文件中除了存有类的版本、字段、方法、接口等描述信息,还有一项是常量池,存有这个类的 编译期生成的各种字面量和符号引用,这部分内容将在类加载后,存放到方法区的运行时常量池中。5. Heap: the largest memory region, shared by all threads, created at JVM startup. It holds all object instances and arrays and is managed by the garbage collector.
Java Memory Model (JMM)
JMM defines how threads interact through shared memory, specifying visibility and ordering rules. All variables reside in main memory, while each thread has its own working memory (a copy of variables). Operations on variables must occur in the working memory, and synchronization actions make changes visible to other threads.
Key actions include lock/unlock, read/load, use/assign, store/write, and the constraints that certain actions cannot appear alone.
Heap Memory Layout
The heap is divided into Young Generation, Old Generation, and (in JDK 8 and later) Metaspace (which replaces the Permanent Generation). The Young Generation uses a copying algorithm with Eden and two Survivor spaces (default ratio 8:1:1). Minor GC occurs when the Young Generation fills up.
The Old Generation uses a mark‑compact algorithm because it collects fewer objects per cycle.
Garbage Collection (GC)
GC determines object reachability using GC Roots (e.g., stack references, static fields, native method references). Objects become eligible for collection after a reachability analysis and, if they have no finalizer or the finalizer has already run, the JVM reclaims their memory.
Common GC algorithms:
Mark‑Sweep: simple but can cause fragmentation.
Copying: avoids fragmentation but requires enough free space.
Mark‑Compact: reduces fragmentation but may be slower when many objects move.
Generational collection: separates young and old generations, applying copying to the young generation and mark‑compact to the old generation.
GC pause types:
Minor GC: collects only the Young Generation.
Major GC: collects the Old Generation when Eden is full.
Full GC: collects the entire heap, including both generations.
HotSpot VM Details
Object creation steps: class loading verification, memory allocation (either pointer‑bumping or free‑list), zero‑initialization, setting object header information, and invoking the method.
Object reference representations:
Handle: a stable indirection that allows the object to move without changing the reference.
Direct pointer: stores the actual address, saving one indirection.
GC implementation notes: HotSpot uses OopMap structures to locate GC Roots efficiently and defines safe points where GC can safely pause threads. Interrupt mechanisms include preemptive and cooperative (poll‑based) interruptions.
CMS collector: a low‑pause collector based on mark‑sweep, performing most work concurrently with application threads, but it can suffer from CPU overhead, floating garbage, and fragmentation.
JVM Optimization Parameters
Typical tuning flags: -Xmn – set Young Generation size. -XX:PetenureSizeThreshold=1000000 – allocate objects larger than 1 MB directly in the Old Generation. -XX:MaxTenuringThreshold – control how many Minor GCs an object can survive before promotion. -Xms and -Xmx – set initial and maximum heap size (often set equal for a stable heap). -XX:MinHeapFreeRatio / -XX:MaxHeapFreeRatio – control heap expansion/compression thresholds. -XX:+UseParallelGC / -XX:+UseParallelOldGC – enable parallel collectors for higher throughput. -XX:+UseConcMarkSweepGC – enable the low‑pause CMS collector. -XX:SurvivorRatio=3 – set the ratio between Survivor and Eden spaces.
Class Loading Mechanism
Class loading consists of three phases: Loading (reading binary data), Linking (verification, preparation, and resolution), and Initialization (executing static initializers).
Verification checks class file structure, semantics, bytecode safety, and binary compatibility.
Resolution replaces symbolic references with direct references.
Initialization occurs when a class is actively used (e.g., new instance, static field access, static method call, reflection, subclass initialization, or the main class at JVM startup).
The JVM follows the parent‑delegation model: a class loader first delegates the request to its parent; only if the parent cannot find the class does the child attempt to load it.
Three built‑in class loaders:
Bootstrap (native, loads core Java classes).
Extension (loads from the extension directories).
System/Application (loads from the classpath).
Custom class loaders can be created by extending java.lang.ClassLoader, overriding findClass, and optionally providing decryption or remote loading capabilities.
Classes loaded by the built‑in loaders are never unloaded, while those loaded by user‑defined loaders can be garbage‑collected when no longer reachable.
Additional Topics
JDK vs JRE: JDK contains development tools and libraries; JRE provides the runtime environment.
Java source files are compiled to bytecode (.class) and then interpreted or JIT‑compiled by the JVM into native machine code.
(End)
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
