How to judge whether the subject is dead? (Two methods)

How to judge whether the subject is dead? (Two methods)

Almost all object instances are stored in the heap. The first step before garbage collection on the heap is to determine which objects need to be recycled (that is, objects that are dead and can no longer be used in any way).

There are two ways to judge.

1. Reference counting method

Add a reference counter to the object. Whenever there is a reference to it, the counter value is increased by 1; when the reference becomes invalid, the counter is decreased by 1; an object whose counter is 0 at any time cannot be used anymore.

We can see that the reference counting method is simple in principle and efficient in judgment, but in the Java field, at least in mainstream Java virtual machines, this method is not used to manage memory.

The main reason may be: in the case of circular references between two objects, the counter will never be 0 at this time, making it impossible to recycle it.

public class Test {
    
    

    public Object instance = null;

    public static void main(String[] args) {
    
    
        Test a = new Test();
        Test b = new Test();
        a.instance = b;
        b.instance = a;
        a = null;
        b = null;
        doSomething();
    }
}

In the above code, the object instances referenced by a and b hold each other's object references, so when we remove the references to the a and b objects, there are still references between the two objects, resulting in two The Test object cannot be recycled.

2. Reachability analysis algorithm

The basic idea of ​​this algorithm is to use a series of objects called "GC Roots" as the starting point. From these nodes, search downwards. The path the nodes traverse is called the reference chain. When an object is connected to the GC Roots without any reference chain If it is, it proves that the object is unusable.

As shown in the figure below, objects object 5, object 6, and object 7, although they are related to each other, they are not reachable to GC Roots, so they will be judged as recyclable objects.
Insert picture description here

Guess you like

Origin blog.csdn.net/hello_cmy/article/details/105874385