There are two types of garbage collection algorithms: reference counting and reachability analysis.
Reference counter: The implementation is very simple. For an object A, as long as any object refers to A, the reference counter of A is increased by 1, and when the reference is invalid, the reference counter is decreased by 1. As long as the value of the reference counter of object A is 0, object A can no longer be used.
But there are problems: citation and Dereference is accompanied by addition and subtraction, which affects performance, and it is difficult to deal with circular references.
As shown in the figure, there is a circular application, so it can never be recycled.
Accessibility analysis: The basic idea of this algorithm is to use a series of objects called “GCRoots” as the starting point, starting from these nodes and searching downwards. The path taken by the search is called a reference. Chain (ReferenceChain), when an object is connected to GCRoots without any reference chain
(in the words of graph theory, from GCRoots to the object is unreachable), it proves that the object is unavailable. As shown in the figure, the Object5,6,7 are recyclable objects
In the Java language, the objects that can be used as GC Roots include the following: 1. Virtual machine stack (local The object referenced in the variable table). 2. Objects referenced by class static properties in the method area 3. Objects referenced by constants in the method area 4. Objects referenced by JNI (in general, Native methods) in the local method stack
< /p>