[Repost] Java Garbage Collection: Object Management and Memory Optimization
Java’s automatic memory management is mainly about two things: allocating memory for objects and reclaiming memory from objects. Its main job is managing how objects are allocated and collected in the heap.
Because the Java heap is the primary region managed by the garbage collector, it is often called the GC Heap (Garbage Collected Heap). From a garbage collection standpoint, nearly all modern collectors use generational collection algorithms, so the Java heap is split into the Young Generation and the Old Generation, and more finely into Eden, From Survivor, and To Survivor spaces. Subdividing the heap like this lets the JVM reclaim memory more effectively and allocate it faster.
1. How JVM memory allocation and garbage collection work
Basic structure of the heap:

In the diagram above, Eden, From Survivor0 (“From”), and To Survivor1 (“To”) all belong to the Young Generation, while Old Memory belongs to the Old Generation.
In most cases, objects are allocated in Eden first. If an object survives a Young Generation GC, it moves into s0 or s1 and its age increases by 1 (an object moving from Eden to Survivor starts at age 1). Once its age reaches a certain threshold (15 by default), it gets promoted to the Old Generation. You can configure this promotion threshold with -XX:MaxTenuringThreshold.
Dynamic tenuring threshold calculation code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 uint ageTable::compute_tenuring_threshold(size_t survivor_capacity) {
// survivor_capacity is the size of the survivor space
size_t desired_survivor_size = (size_t)((((double)survivor_capacity)*TargetSurvivorRatio)/100);
size_t total = 0;
uint age = 1;
while (age < table_size) {
// the sizes array holds the total size of objects at each age
total += sizes[age];
if (total > desired_survivor_size) {
break;
}
age++;
}
uint result = age < MaxTenuringThreshold ? age : MaxTenuringThreshold;
...
}
After this GC cycle, both Eden and the “From” space have been cleared. At that point, “From” and “To” swap roles: the new “To” was the previous “From”, and the new “From” was the previous “To”. Either way, the Survivor space named “To” is always guaranteed to be empty. Minor GC repeats this process until the “To” space fills up; once “To” is full, all objects are moved into the Old Generation.
1.1 Objects are allocated in Eden first
Mainstream garbage collectors today use generational collection algorithms, which is why the heap is split into the Young Generation and the Old Generation. Each generation can then use whichever collection algorithm fits it best.
Most of the time, objects are allocated in the Eden space of the Young Generation. When Eden doesn’t have enough room for a new allocation, the JVM triggers a Minor GC. Let’s test this in practice.
Test:
1 | public class GCTest { |
Run it as follows:
Add the JVM flag: -XX:+PrintGCDetails
Output (note: the red label in the screenshot is inaccurate; it should refer to JDK 1.7’s Permanent Generation):

From the screenshot above, you can see Eden is almost completely full (even if the program does nothing at all, the Young Generation already uses over 2,000 KB of memory). Now, what happens if we allocate allocation2 as well?
1 | allocation2 = new byte[900*1024]; |

Why did this happen? By the time we tried to allocate allocation2, Eden was nearly full. As we just saw, when Eden runs out of room, the JVM kicks off a Minor GC. During that GC, the JVM discovers that allocation1 won’t fit into the Survivor space, so it uses the allocation guarantee mechanism to promote the Young Generation object early into the Old Generation. Since the Old Generation has plenty of space for allocation1, no Full GC is triggered. After the Minor GC finishes, later allocations still go to Eden as long as they fit. You can verify this by running the following code:
1 | public class GCTest { |
1.2 Large objects go straight to the Old Generation
Large objects are objects that need a large contiguous block of memory (such as long strings or big arrays).
Why send them straight to the Old Generation?
To avoid the performance hit of copying large objects around under the allocation guarantee mechanism.
1.3 Long-lived objects move to the Old Generation
Since the JVM manages memory using generational collection, it needs a way to tell which objects belong in the Young Generation and which belong in the Old Generation. To track this, the JVM keeps an Age counter for every object.
If an object is born in Eden, survives its first Minor GC, and fits in the Survivor space, it gets moved into Survivor with its age set to 1. Every time it survives another Minor GC in Survivor, its age increments by 1. Once its age hits a set threshold (15 by default), it is promoted to the Old Generation. You can configure that promotion threshold with -XX:MaxTenuringThreshold.
1.4 Dynamic object age determination
In most cases, objects are allocated in Eden first. If an object survives a Young Generation GC, it moves into s0 or s1 and its age increases by 1 (Eden -> Survivor starts the object at age 1). Once its age reaches a certain threshold (15 by default), it gets promoted to the Old Generation, configurable via -XX:MaxTenuringThreshold.
Correction (issue552): “When HotSpot iterates over objects in Survivor, it accumulates their total size in ascending order of age. As soon as the cumulative size up to a given age exceeds 50% of the Survivor space (50% is the default, configurable via
-XX:TargetSurvivorRatio=percent; see issue1199), HotSpot takes the smaller of that age andMaxTenuringThresholdas the new tenuring threshold.”Reference from the official JDK 8 documentation: https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html .
Dynamic tenuring threshold calculation code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 uint ageTable::compute_tenuring_threshold(size_t survivor_capacity) {
// survivor_capacity is the size of the survivor space
size_t desired_survivor_size = (size_t)((((double)survivor_capacity)*TargetSurvivorRatio)/100);
size_t total = 0;
uint age = 1;
while (age < table_size) {
// the sizes array holds the total size of objects at each age
total += sizes[age];
if (total > desired_survivor_size) {
break;
}
age++;
}
uint result = age < MaxTenuringThreshold ? age : MaxTenuringThreshold;
...
}Additional note (issue672): The widely repeated claim that the default promotion age is 15 mostly comes from the book Understanding the JVM (
《深入理解 Java 虚拟机》).
If you check Oracle’s official JVM options documentation, here is what it actually says under-XX:MaxTenuringThreshold=threshold:Sets the maximum tenuring threshold for use in adaptive GC sizing. The largest value is 15. The default value is 15 for the parallel (throughput) collector, and 6 for the CMS collector. So the default promotion age is not always 15. It depends on the collector, and for CMS it is 6.
1.5 Regions targeted by GC
In the second edition of Understanding the JVM (p. 92), Zhou Zhiming wrote:
“Old Generation GC (Major GC / Full GC) refers to GC occurring in the Old Generation…”
That statement was corrected in the third edition of Understanding the JVM. Credits to RednaxelaFX (R大) for clarifying this:

Summary:
Specifically for HotSpot VM’s implementation, GC is accurately divided into only two major categories:
Partial GC:
- Young Generation GC (Minor GC / Young GC): collects only the Young Generation.
- Old Generation GC (Major GC / Old GC): collects only the Old Generation. Note that in some contexts, “Major GC” is also used to mean a full-heap collection.
- Mixed GC: collects the entire Young Generation along with part of the Old Generation.
Full GC: collects the entire Java heap and the Method Area.
2. Is an object dead?
Almost all object instances live on the heap. Before the garbage collector can reclaim anything from the heap, its first step is figuring out which objects are dead (objects that can no longer be reached or used in any way).

2.1 Reference counting
Attach a reference counter to each object. Whenever something references the object, increment the counter by 1; whenever a reference goes away, decrement it by 1. Any object whose counter hits 0 can never be used again.
This approach is simple to implement and fast, yet mainstream JVMs do not use it for memory management, mostly because it struggles with circular references between objects. Take the code below: objA and objB reference each other, and nothing else references either of them. Because they keep pointing at each other, neither reference count ever drops to 0, so reference counting cannot tell the GC to collect them.
1 | public class ReferenceCountingGc { |
2.2 Reachability analysis
The basic idea behind reachability analysis is to start from a set of root objects called “GC Roots” and walk downward along object references. The path walked from a root is called a reference chain. If an object has no reference chain connecting it to any GC Root, it is unreachable and eligible for collection.

Objects that qualify as GC Roots include:
- Objects referenced by the JVM stack (local variable tables in stack frames)
- Objects referenced by the Native Method Stack (JNI / native methods)
- Objects referenced by static class fields in the Method Area
- Objects referenced by constants in the Method Area
- All objects held by synchronization locks (
synchronized)
2.3 A closer look at references
Whether you judge an object’s liveness by counting references or by tracing reachability chains, everything comes down to “references.”
Before JDK 1.2, Java’s definition of a reference was traditional: if the value stored in a reference type represents the starting memory address of another block of memory, then that memory represents a reference.
Starting in JDK 1.2, Java expanded the concept into four levels of references, ordered from strongest to weakest: Strong, Soft, Weak, and Phantom.
1. Strong Reference (StrongReference)
Most of the references we write day to day are strong references; they are by far the most common. Think of a strongly referenced object as an essential daily necessity: the garbage collector will never reclaim it. When memory runs out, the JVM would rather throw an OutOfMemoryError and crash the program than arbitrarily collect a strongly referenced object to free up space.
2. Soft Reference (SoftReference)
An object with only soft references is like a nice-to-have item. As long as memory is plentiful, the garbage collector leaves it alone; when memory gets tight, it reclaims these objects. Until the GC collects it, the program can keep using it. Soft references are useful for building memory-sensitive caches.
A soft reference can be paired with a ReferenceQueue. Once the softly referenced object is garbage-collected, the JVM enqueues that SoftReference into the associated queue.
3. Weak Reference (WeakReference)
An object with only weak references is also like a nice-to-have item, except with an even shorter lifespan. Whenever the GC thread scans the memory region it manages and spots an object that is only weakly referenced, it reclaims that object regardless of whether memory is currently plentiful or not. That said, because the GC runs on a very low-priority thread, it might not discover weakly referenced objects right away.
Like soft references, weak references can be paired with a ReferenceQueue so the JVM enqueues the WeakReference once its referent is collected.
4. Phantom Reference (PhantomReference)
True to its name, a phantom reference is barely there at all. Unlike the other three types, it has no effect on an object’s lifecycle. An object holding only a phantom reference is treated as if it had no reference at all and may be collected at any time.
Phantom references exist mainly to track when an object is being garbage-collected.
One key difference from soft and weak references: a phantom reference must be paired with a ReferenceQueue. When the garbage collector is about to reclaim an object and sees it has a phantom reference, it adds that phantom reference to the associated ReferenceQueue before freeing the object’s memory. The program can inspect the queue to learn that the referent is about to be collected and take any needed cleanup action beforehand.
Note that in everyday application design, weak and phantom references are rarely used directly, whereas soft references show up more often, because soft references help the JVM reclaim garbage memory faster, keep the system stable, and prevent OutOfMemoryError crashes.
2.4 Unreachable objects are not “doomed to die”
Even if an object comes up unreachable during reachability analysis, it isn’t immediately “doomed to die.” Instead, it enters a temporary “reprieve” phase. To formally pronounce an object dead, the JVM puts it through at least two marking passes. After being marked unreachable the first time, the object is checked to see whether running its finalize() method is necessary. If the object did not override finalize(), or if finalize() has already been called by the JVM once before, the JVM treats it as unnecessary.
If finalize() does need to run, the object is placed in a queue for a second marking pass. Unless it manages to reattach itself to some object on a live reference chain during finalize(), it will finally be collected for real.
2.5 How to tell if a constant is obsolete
Garbage collection in the Runtime Constant Pool primarily targets obsolete constants. So how does the JVM decide a constant is obsolete?
Since JDK 1.7, the JVM moved the Runtime Constant Pool out of the Method Area and carved out space for it inside the Java Heap.
🐛 Correction (see issue747, reference):
- Before JDK 1.7, the Runtime Constant Pool (logically containing the String Constant Pool) lived in the Method Area, which HotSpot implemented as the Permanent Generation (PermGen).
- In JDK 1.7, only the String Constant Pool was moved out of the Method Area into the Heap. The rest of the Runtime Constant Pool stayed in the Method Area (HotSpot’s PermGen).
- In JDK 1.8, HotSpot removed PermGen and replaced it with Metaspace. The String Constant Pool stayed in the Heap, and the Runtime Constant Pool stayed in the Method Area; only the implementation of the Method Area changed from PermGen to Metaspace.
Suppose the string "abc" sits in the String Constant Pool. If no String object anywhere currently references "abc", then "abc" is an obsolete constant. If GC runs and reclaiming it is needed, the system clears "abc" out of the constant pool.
2.6 How to tell if a class is unused
Garbage collection in the Method Area mainly targets unused classes. How does the JVM decide whether a class is unused?
Checking whether a constant is obsolete is straightforward, but the bar for declaring a class “unused” is much stricter. A class must satisfy all three of the following conditions at the same time:
- All instances of the class have been collected, meaning no instances of that class remain in the Java heap.
- The
ClassLoaderthat loaded the class has been collected. - The
java.lang.Classobject representing the class is not referenced anywhere, so the class’s methods cannot be accessed anywhere via reflection.
The JVM may unload a class that meets all three conditions. Notice the word “may”: unlike regular objects, an unused class is not guaranteed to be collected just because it is no longer used.
3. Garbage collection algorithms

3.1 Mark-Sweep algorithm
This algorithm has two phases: “Mark” and “Sweep.” First it marks all live objects that should not be collected; once marking finishes, it sweeps away all unmarked objects in one pass. It is the most basic collection algorithm, and later algorithms evolved to fix its shortcomings. Mark-Sweep has two obvious drawbacks:
- Efficiency issues
- Space issues (sweeping leaves behind lots of fragmented, non-contiguous free space)

3.2 Mark-Copy algorithm
To solve the efficiency problem, the Mark-Copy (Copying) algorithm was introduced. It splits available memory into two equal halves and uses only one half at a time. When the active half fills up, all surviving objects are copied over to the other half, and the entire used half is cleared in one shot. That way, every collection reclaims half of the memory region at once.

3.3 Mark-Compact algorithm
Designed with the Old Generation in mind, Mark-Compact keeps the same marking phase as Mark-Sweep. Instead of sweeping dead objects in place, it slides all surviving objects toward one end of the memory space and then wipes everything past the boundary cleanly.

3.4 Generational collection algorithm
Modern JVMs all use generational collection. There is no brand-new algorithm here; it simply splits memory into regions based on how long objects tend to live. Typically, the Java heap is divided into the Young Generation and the Old Generation so each region can pick the collection algorithm that suits it best.
In the Young Generation, most objects die quickly on every GC cycle, so Mark-Copy works great: you only pay the cost of copying the small fraction of survivors. In the Old Generation, survival rates are much higher and there is no extra space for an allocation guarantee, so you have to use Mark-Sweep or Mark-Compact instead.
Follow-up interview question: Why does HotSpot split the heap into the Young Generation and the Old Generation?
Answer using the generational collection rationale above.
4. Garbage collectors

If collection algorithms are the methodology for reclaiming memory, garbage collectors are the concrete implementations.
Even though we compare different collectors here, the goal isn’t to crown a single “best” collector. To this day, there is no single best or one-size-fits-all garbage collector. All we can do is pick the collector that fits our workload. Think about it: if a universally perfect collector existed for every scenario, HotSpot wouldn’t ship with so many different ones.
4.1 Serial collector
The Serial collector is the simplest and oldest garbage collector. As the name implies, it is single-threaded. Here, “single-threaded” doesn’t just mean it uses one GC thread to do the work. More importantly, it must pause all application worker threads (“Stop The World”) until collection finishes.
Uses Mark-Copy in the Young Generation and Mark-Compact in the Old Generation.

JVM designers obviously know how painful Stop-The-World pauses are for user experience, so later collectors have steadily shrunk pause times (pauses still exist, and the search for better collectors continues).
Does the Serial collector have any edge over other collectors? Yes: it is simple and efficient (compared to a single thread of any other collector). With zero thread-coordination overhead, Serial achieves very high single-threaded collection efficiency, so it is a solid choice for JVMs running in Client mode.
4.2 ParNew collector
ParNew is just the multithreaded version of the Serial collector. Aside from using multiple threads for garbage collection, everything else (control flags, collection algorithms, reclamation policies, and so on) is identical to Serial.
Uses Mark-Copy in the Young Generation and Mark-Compact in the Old Generation.

ParNew is a go-to choice for many JVMs running in Server mode: aside from Serial, it is the only Young Generation collector that can work together with CMS (the first truly concurrent collector, covered below).
Quick refresher on Parallel vs. Concurrent:
Parallel: Multiple GC threads work in parallel, while application threads remain paused and waiting.
Concurrent: Application threads and GC threads run at the same time (not necessarily strictly in parallel; they may interleave), so the user program keeps running while the GC runs on another CPU.
4.3 Parallel Scavenge collector
Parallel Scavenge is also a multithreaded collector using Mark-Copy, and at first glance it looks almost identical to ParNew. So what makes it different?
1 | -XX:+UseParallelGC |
Parallel Scavenge focuses on throughput (making the most efficient use of CPU), whereas collectors like CMS focus on minimizing application pause times (improving user experience). Throughput is the ratio of CPU time spent running user code to total CPU time. Parallel Scavenge exposes plenty of tuning knobs to target either a pause-time goal or maximum throughput. If you aren’t deeply familiar with GC internals and manual tuning feels daunting, pairing Parallel Scavenge with its adaptive sizing policy and letting the JVM handle memory tuning automatically is a solid option.
Uses Mark-Copy in the Young Generation and Mark-Compact in the Old Generation.

This is the default collector in JDK 1.8.
You can verify it with java -XX:+PrintCommandLineFlags -version:
1 | -XX:InitialHeapSize=262921408 -XX:MaxHeapSize=4206742528 -XX:+PrintCommandLineFlags -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseParallelGC |
By default, JDK 1.8 uses Parallel Scavenge + Parallel Old. Specifying -XX:+UseParallelGC also enables -XX:+UseParallelOldGC automatically; you can turn it off with -XX:-UseParallelOldGC.
4.4 Serial Old collector
The Old Generation counterpart to the Serial collector, and likewise single-threaded. It has two main uses: pairing with Parallel Scavenge in JDK 1.5 and earlier, and working as the fallback collector for CMS.
4.5 Parallel Old collector
The Old Generation counterpart to Parallel Scavenge, using multiple threads and the Mark-Compact algorithm. In workloads where throughput and CPU utilization matter most, Parallel Scavenge + Parallel Old is a top contender.
4.6 CMS collector
CMS (Concurrent Mark Sweep) aims for the shortest possible GC pause times, so it fits applications where responsiveness and user experience matter.
CMS is HotSpot’s first truly concurrent collector: the first time GC threads and user threads could run (mostly) at the same time.
As Mark Sweep in its name suggests, CMS is built on the Mark-Sweep algorithm, and its workflow is more involved than the collectors above. It runs in four steps:
- Initial Mark: Pauses all other threads and records objects directly reachable from GC Roots. This step is very fast.
- Concurrent Mark: Runs GC threads alongside application threads, traversing the object graph to record reachable objects. By the end of this phase, that graph is not guaranteed to reflect every currently reachable object, because user threads keep mutating object references while marking is in progress. So the algorithm tracks any references modified during this phase.
- Remark: Fixes the marking records for objects whose references changed while application threads kept running during Concurrent Mark. This pause is usually slightly longer than Initial Mark, though still far shorter than Concurrent Mark.
- Concurrent Sweep: Application threads continue running while GC threads sweep unmarked memory regions.

As its name implies, CMS brings major strengths: concurrent collection and low pause times. Still, it has three clear drawbacks:
- Sensitive to CPU resources
- Cannot handle floating garbage
- Because it relies on Mark-Sweep, it leaves behind substantial memory fragmentation after collection
4.7 G1 collector
G1 (Garbage-First) is a server-oriented garbage collector aimed at machines with multiple processors and large memories. It delivers high throughput while meeting GC pause-time targets with high probability.
Regarded as a major milestone in HotSpot VM starting in JDK 1.7, G1 brings the following features:
- Parallel and Concurrent: G1 takes full advantage of multi-CPU and multi-core hardware to shorten Stop-The-World pauses. Some GC work that previously required pausing Java threads in other collectors can run concurrently with Java application threads in G1.
- Generational Collection: Even though G1 manages the entire GC heap on its own without pairing with another collector, it still keeps the concept of generations.
- Space Compaction: Unlike CMS’s Mark-Sweep approach, G1 behaves like a Mark-Compact collector globally and like a Mark-Copy collector locally between regions.
- Predictable Pauses: Another major advantage over CMS. Both G1 and CMS care about short pauses, but G1 goes further by building a predictable pause-time model, so users can specify a target maximum pause time within any time window of M milliseconds.
G1 roughly operates in four phases:
- Initial Mark
- Concurrent Mark
- Final Mark
- Live Data Counting and Evacuation (Mixed/Screening Collection)
G1 maintains a priority list in the background and, given the allowed pause budget, prioritizes collecting the Regions with the highest reclamation payoff (which is where the name “Garbage-First” comes from). Splitting the heap into Regions and reclaiming them by priority lets G1 get the highest possible collection efficiency within bounded time, breaking the heap into manageable pieces.
4.8 ZGC collector
Like ParNew (used with CMS) and G1, ZGC also uses a Mark-Copy algorithm, but with major architectural improvements.
In ZGC, Stop-The-World pauses become far rarer and shorter!
For a deep dive, see: Exploration and Practice of the Next-Generation Garbage Collector ZGC (Chinese, Meituan Tech Blog)
References
- Understanding the JVM: Advanced Features and Best Practices (2nd Edition) (
《深入理解 Java 虚拟机:JVM 高级特性与最佳实践(第二版)》) - https://my.oschina.net/hosee/blog/644618
- https://docs.oracle.com/javase/specs/jvms/se8/html/index.html
