How does the garbage collection mechanism determine whether an object is useful and where to clean it up?

One of the advantages of this algorithm is that it is real-time, as long as the value of the reference
counter of the object is 0, it will be recycled immediately. The mark-sweep algorithm described next will not be reclaimed immediately when the value of the reference counter of the object is 0.
root object
In the mark-sweep algorithm, the following objects are called root objects
1. Objects referenced by variables on the stack (the stack stores references to objects)
2. Objects referenced by static
variables Accessible objects
If there is a variable a on the stack that references an object, then the object is accessible, and if a field in the object references another object b, then b is also accessible. Accessible objects are also called live objects. Introduction to the
Mark Sweep Algorithm


The algorithm has two phases. 
1. Marking phase: find all accessible objects and mark them 
2. Clearing phase: traverse the heap and recycle unmarked objects


Remarks :
This algorithm is generally applied to the old age, because the object life cycle of the old age is relatively long.
Marking phase algorithm The


pseudo code is similar to the following:


for each root variable r
    mark (r);
sweep ();


In order to distinguish whether the object is live, a marked field can be added to each object, which has a default value when the object is created is false 
. Suppose there is an object p, and the p object indirectly references other objects, then a recursive algorithm can be used to mark, for example:


void mark(Object p)
    if (!p.marked)
        p.marked = true;
        for each Object q referenced by p
            mark (q);


This mark method will exit only when all objects have been marked.
Clearing Phase Algorithm


In this phase, it is necessary to traverse all objects in the heap, find out the unmarked objects, and recycle them. At the same time, the marked field of those marked objects will be reset to false for the next garbage collection. 
The pseudo code is as follows:


void sweep ()
    for each Object p in the heap
        if (p.marked)
            p.marked = false
        else
            heap.release (p);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324649382&siteId=291194637