Reference counting algorithm
The idea of the algorithm is simple and easy to implement. We add a reference counter to the object, and when there is a place to reference it, the reference counter adds one, and when the reference fails, the counter is reduced by one, and when the counter is 0 o'clock, the object cannot be referenced again.
Objective evaluation, the algorithm is highly efficient, in many cases is a good algorithm, but at least the mainstream Java Virtual machine is not adopted by this algorithm. The reason is that the algorithm cannot resolve circular reference problems between objects.
What is a circular reference? I think it is a nested reference between objects, the object B is assigned to the field in object a instance, and then the object A is assigned to the field in object B instance, thus forming a nested mutual reference relationship, the reference counter will never be 0, according to the algorithm, Two objects will naturally not be recycled, but this is not the case, the virtual machine has successfully reclaimed two objects (refer to the "in-depth understanding of Java Virtual Machine" 63 page code).
Accessibility analysis algorithm
It can be seen intuitively that determining whether an object is alive can check if the object is associated with a GC roots, or from GC roots to whether there is a path to the object, which is also known as a reference chain (Reference Chain). If available, the object can be referenced, and if the object is unreachable, the object is not referenced.
In the Java language, objects that can be used as GC roots include the following:
- Objects referenced in the virtual machine stack (local variable table in the stack frame)
- Object referenced by class static property in method area
- Objects referenced by constants in the method area
- The object referenced by JNI (that is, the general native method) in the local method stack