How Java Determines Object Reusability: Reference Counting vs Reachability Analysis
This article explains Java's two primary garbage‑collection techniques—reference counting and reachability analysis—detailing their principles, drawbacks such as circular reference issues, and why modern JVMs favor reachability analysis to safely reclaim memory.
In Java, determining whether an object can be reclaimed is mainly done via two methods: reference counting and reachability analysis.
Reference Counting
Principle
Each object has a reference counter stored in extra memory; the counter increments when a reference is created and decrements when a reference is lost. When the counter reaches zero, the object can be reclaimed.
Drawbacks
Although simple and fast, reference counting cannot resolve circular references. For example, objects A and B reference each other; when external references disappear, both counters stay non‑zero, preventing reclamation and causing memory leaks.
class ClassA {
// ClassA holds a reference to ClassB
private ClassB refToB;
// Set reference to ClassB
public void setRefToB(ClassB b) {
this.refToB = b;
}
}
class ClassB {
// ClassB holds a reference to ClassA
private ClassA refToA;
// Set reference to ClassA
public void setRefToA(ClassA a) {
this.refToA = a;
}
}
public class CircularReferenceTest {
public static void main(String[] args) {
// Create instances of ClassA and ClassB
ClassA a = new ClassA();
ClassB b = new ClassB();
// a references b
a.setRefToB(b);
// b references a
b.setRefToA(a);
// Remove external references
a = null;
b = null;
}
}Reachability Analysis
Principle
Starting from a set of objects called “GC Roots”, the algorithm traverses reference chains; all objects reachable from the roots are marked as live. Objects not reachable from any GC root are considered garbage and can be reclaimed.
Thus, mainstream Java garbage collectors use reachability analysis because it effectively handles circular references and prevents memory leaks.
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.
Xuanwu Backend Tech Stack
Primarily covers fundamental Java concepts, mainstream frameworks, deep dives into underlying principles, and JVM internals.
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.
