Inside the JVM: Unraveling Memory Areas, GC, and Class Loading
This article provides a comprehensive overview of the Java Virtual Machine, covering its runtime data areas, the Java Memory Model, heap organization, garbage‑collection algorithms, HotSpot implementation details, JVM tuning parameters, and the class‑loading mechanism.
Java Runtime Data Areas
The JVM partitions memory used by a Java program into several distinct runtime data areas, each with its own purpose and lifecycle:
Program Counter (PC) Register : Thread‑local pointer to the next bytecode instruction.
Java Virtual Machine Stack : Stores stack frames for each method invocation; each frame holds local variables, operand stack, and dynamic linking information.
Native Method Stack : Supports execution of native (C/C++) methods; also thread‑private.
Method Area : Holds class metadata, static variables, constant pool, and JIT‑compiled code; shared among threads.
Heap : The largest memory region, shared by all threads, where Java objects are allocated.
Java Memory Model (JMM)
The JMM defines how threads interact through shared memory:
All variables reside in main memory; each thread has a private working memory that holds copies of the variables it uses.
Thread actions (read, write, lock, unlock, etc.) must occur via the working memory, with explicit synchronization actions making changes visible to other threads.
Visibility and ordering guarantees are provided by the JMM, ensuring that writes become visible to other threads at well‑defined points.
Heap Memory Layout
The heap is divided into generations to optimize garbage collection:
Young Generation : Uses a copying algorithm; consists of Eden and two Survivor spaces (default ratio 8:1:1). Minor GC frequently reclaims most objects here.
Old Generation (Tenured) : Uses a mark‑compact algorithm; collects long‑lived objects.
MetaSpace (replaces PermGen in JDK 8) : Stores class metadata; allocated in native memory.
Garbage Collection Overview
GC determines object reachability using the "GC Roots" algorithm. Objects unreachable from any root are eligible for reclamation. Common GC algorithms include:
Mark‑Sweep : Simple but can cause fragmentation.
Copying (Copy‑On‑Write) : Eliminates fragmentation; used for the young generation.
Mark‑Compact : Compacts live objects to reduce fragmentation; used for the old generation.
Generational Collection : Combines copying for young generation and mark‑compact for old generation.
Typical GC types:
Minor GC – collects only the young generation.
Major GC – collects the old generation.
Full GC – collects the entire heap.
A、When the JVM cannot allocate a new object, Minor GC is triggered more frequently.
B、Minor GC does not affect the old generation.HotSpot JVM Details
Object Creation Process :
Resolve the symbolic reference of the class from the constant pool.
Allocate memory in the heap (pointer bump or free‑list, depending on heap layout).
Initialize the object header (hash code, GC age, class pointer, etc.).
Execute the constructor to set up the object's state.
Object Reference Types :
Handle (indirect) – a stable pointer stored in a handle pool; useful when objects move during GC.
Direct pointer – the actual memory address; faster but requires object relocation handling.
GC Implementation :
HotSpot uses OopMap data structures to locate GC roots efficiently.
Safe points are inserted by the JIT compiler; GC can only pause threads at these points.
Two interruption strategies: pre‑emptive (stop all threads) and cooperative (threads poll a flag).
CMS Collector (low‑pause concurrent collector):
A. Initial Mark – marks objects directly reachable from GC roots.
B. Concurrent Mark – traverses the object graph in parallel with application threads.
C. Final Mark – corrects marks changed during the concurrent phase.
D. Concurrent Sweep – reclaims memory of unmarked objects.CMS drawbacks include higher CPU usage, inability to collect “floating” garbage, and potential fragmentation leading to Full GC.
JVM Optimization Parameters
Common tuning flags: -Xms and -Xmx – set initial and maximum heap size; equal values give a stable heap. -XX:SurvivorRatio=3 – configures the ratio between Eden and Survivor spaces (default 8:1:1). -XX:MinHeapFreeRatio / -XX:MaxHeapFreeRatio – control when the heap expands or shrinks. -XX:+UseParallelGC / -XX:+UseParallelOldGC – enable parallel collectors for higher throughput. -XX:+UseConcMarkSweepGC – enable the low‑pause CMS collector. -XX:+LargePageSizeInBytes – use large memory pages to improve addressing efficiency.
Class Loading Mechanism
Class loading proceeds through four phases:
Loading : Read the binary .class data into the method area.
Linking :
Verification – checks class file structure, semantics, bytecode safety, and binary compatibility.
Preparation – allocates static fields and sets default values.
Resolution – transforms symbolic references into direct references.
Initialization : Executes static initializers and assigns proper values to static fields.
The parent‑delegation model ensures that a class loader first asks its parent to load a class, preventing user‑defined loaders from overriding core Java classes.
Three built‑in class loaders:
Bootstrap (native, loads core libraries).
Extension (loads from jre/lib/ext).
System/Application (loads from the classpath).
Custom class loaders extend java.lang.ClassLoader and override findClass to load classes from unconventional sources (e.g., databases, encrypted files).
Class unloading is possible only for classes loaded by user‑defined loaders; classes loaded by the three built‑in loaders remain resident for the lifetime of the JVM.
Source: Huangy远, SegmentFault (https://segmentfault.com/a/1190000014395186)
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.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
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.
