Garbage Collection - Reference counting circular reference problem

  Realization of ideas: add a reference to the object counter. Whenever there is a reference to its place, the counter is incremented; when referring to a failure counter is decremented. At any time counter for the object 0 it is no longer being used.

  Advantages: simple, high efficiency.

  Disadvantages: difficult to resolve mutual reference cycle between objects. A reference B, B referenced A - circular reference (reference counting algorithm) since the other references A, B with each other, causing the reference count is not 0, so they can not be recovered GC

 1 public class MyObject {
 2     public Object ref = null;
 3     public static void main(String[] args) {
 4         MyObject myObject1 = new MyObject();
 5         MyObject myObject2 = new MyObject();
 6         myObject1 = myObject2;
 7         myObject2 = myObject1;
 8         myObject1 = null;
 9         myObject2 = null;
10     }
11 }

To myObject1 objects, for example:

  1, the code execution line6, myObject1 reference count of 2.

  2, myObject1 = null, myObject1 reference count of 1.

  3, myObject1 = 0, the garbage collector to garbage collection, myObject1 = myObject2; because myObject1 hold a reference myObject2, but to clear out the references provided that the object referenced myObject2 be recovered. The myObject2 = myObject1, eventually an infinite loop.

  4, myObject1 and myObject2 are 1, resulted in garbage collection.

Reference counting circular reference problem

Guess you like

Origin www.cnblogs.com/gogogofh/p/11113744.html