As we know, the virtual machine determines whether an object is “dead” by determining whether it still has references to it. How does the virtual machine determine if there is a reference to an object?

At present, there are two algorithms to determine whether an object is alive or not:

  • Reference counting algorithm
  • Accessibility analysis algorithm

Reference counting algorithm

Every object has a counter. When the object is referenced by a variable or by another object, the counter value increases by one. When the reference is invalid, the counter value decreases by one.

Accessibility analysis algorithm

Through a series of objects called “GC Roots” as the starting point, the path searched down is called “reference chain”. When there is no reference chain from an object to GC Roots, i.e. from GC Roots to this object is unreachable, the object is proved to be unavailable.

2.1 What objects can be used as GC Roots

  1. Objects referenced in the virtual machine stack local variable table
  2. An object referenced by a static variable in a method area
  3. The object referenced by the constant in the method area
  4. Objects referenced by Native methods in the Native method stack

Three, two ways to compare

  • Although reference counting method is simple and efficient, it is easy to appear cyclic reference.
  • Reachability analysis algorithm is the main discriminant method because it does not have cyclic reference problem.

Circular reference examples:

public class ReferenceCounting {
  public Object data = null;

  public static void test(a)  {
            ReferenceCounting objA = new ReferenceCounting();
            ReferenceCounting objB = new ReferenceCounting();
            
            objA.data = objB;
            objB.data = objA;
            
            objA = null;
            objB = null; }}Copy the code

The two objects objA and objB originally pointed to have no references to them, but because the member variables refer to each other, the reference count is not zero and the garbage collector cannot collect them.