java object survived decision algorithm

In the pile of almost all object instances kept the java world, the garbage collector in front of the heap for recycling, the first thing is to determine which among these objects still "alive" with, which had been "dead."

Reference counting algorithm

Add a reference to an object counter, whenever a reference to its place, the counter is incremented by 1; when referring to the failure, the counter is decremented by 1; any time counter is zero when the object is being used is not possible.

Said reference counter achieve substantial simple, determination efficiency is very high, in most cases he is a good algorithm, but the mainstream java virtual machine did not choose the reference counter algorithm to manage memory, the main reason is that he is cycle between difficult to understand object reference problem.

For example, objects obj1 and obj2 are other references, in addition to two other objects no longer have any references, in fact, have two objects can not be accessed, but because they reference each other with each other, resulting in their references counter is not 0, then the reference count algorithms can not notify them recovered GC collector, specifically the following code:

public class RefCountGC {

        public Object instance = null;

        public static void test() {

              RefCountGC obj1 = new RefCountGC();

              RefCountGC obj2 = new RefCountGC();

              obj1.instance = obj2;

              obj2.instance = obj1;

              obj1 = null;

              obj2 = null;  

        }

}

Reachability analysis algorithm

java (including many mainstream programming languages ​​such as C #) whether the mainstream implementations are judged by reachability analysis objects survived. The basic idea of ​​the algorithm is a series called "GC Roots" object as a starting point, to start the search downward from these nodes, called search path traversed chain of references, when an object has no references to GC Roots when connected to the chain, then the proof is not available object.

 

Reachability analysis algorithms determine whether the object recyclable

In the java language, an object can be used as the GC Roots of the following categories:

1, the virtual machine stack (Local Variable Table stack frame) referenced objects

2, a race class method area property reference object

3. The method of constant reference object region

4, native method stacks in JNI (ie, the general said native method) the object referenced by

the original address: https: //www.jianshu.com/p/9847a9499dde
if infringement please contact the author deleted

Published 10 original articles · won praise 0 · Views 4426

Guess you like

Origin blog.csdn.net/xiaohuihui501/article/details/103934239