Determining whether the object of two algorithms cold

Determine whether an object is garbage algorithm mainly has the following two:

  • Reference counting algorithm
  • Reachability analysis algorithm

Let's look at each.

 

Reference counting algorithm

Add a reference count for the object, when the object increases a reference counter is incremented when the reference counter is decremented failure. Reference count for the object 0 may be recovered.

advantage:

  • Simple
  • High efficiency, less impact on the execution of the program

Reference counting algorithm in most cases it is a good algorithm, but also some of the more well-known application cases, such as the use of FlashPlayer ActionScript3, Python language uses reference counting algorithm to memory management.

But the disadvantage of reference counting algorithm is also very obvious, it is difficult to solve the problem of mutual circulation between object references, so the mainstream Java virtual machine inside the application does not use reference counting algorithm to manage memory .

Examples cited circulation:

public class ReferenceCounterProblem{

    public ReferenceCounterProblem instance = null;

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

In this case, the original points a and b of the object is no longer accessible, and b a pointed object (as a and b set to null), but using a reference counting algorithm, then, reference in this case counters are 1, and will not be changed, so that two objects can not be recovered at this time memory leak occurs.

 

Reachability analysis algorithm

In the mainstream to achieve mainstream commercial programming languages ​​(including Java, C #, etc.), the are called by reachability analysis algorithm to determine whether the object alive.

The basic idea of the algorithm is a series called the "GC Roots" objects as a starting point, to start the search down from these nodes, called search path traversed chain of references, when an object has no references to GC Roots when connected to the chain, it is proved that this object can be recycled. Instead, the reachable objects are alive.

Below
Here Insert Picture Description
Object 1 ~ 4 are survival of the subject is determined, and the Object 5 ~ 7 were determined to recyclable.

GC Roots can be used as main targets the following four categories:

  • VM stack objects referenced in the local variable table
  • Native method stacks in the JNI (i.e. those native methods in the API) objects referenced
  • Method static property class object referenced by region
  • Method zone object literal references

Guess you like

Origin blog.csdn.net/u013568373/article/details/94171039