How the garbage collector determines which objects to recycle:
Reference counting method
Many textbooks determine whether an object survives the algorithm is this: Add a reference counter to the object, whenever there is a reference to it, the counter value is added 1, when the reference fails, the counter value is reduced by 1, any time the counter is 0 of the object is impossible to be used again.
Objectively speaking, the implementation of the reference technology algorithm is simple, the decision efficiency is very high, in most cases it is a good algorithm, there are some more famous application cases, such as Microsoft COM technology, using ActionScript 3 Flashplayer, The Python language, as well as the widely used squirrel in the game scripting World, uses a reference counting algorithm for memory management. But the Java language is not selected, the main reason is that it is difficult to solve the problem of mutual circular reference between objects .
Root Search algorithm
in mainstream commercial programming languages (Java and C #), the root search algorithm (GC Roots tracing) is used to determine whether an object survives. The basic idea of this algorithm is to use a series of objects called "GC Roots" as the starting point, starting from these nodes to search down, the path of the search is called the reference chain (Reference Chain), when an object to the GC Roots no reference chain is connected (in the case of graph theory, from GC roots to the object unreachable), it proves that this object is not available.
The following are some of the objects that can be used as GC roots in the Java language:
The reference object in the virtual machine stack (the local variable table in the stack frame).
The object referenced by the class static property in the method area.
The object referenced by a constant in the method area.
The object referenced by the JNI (that is, the native method) in the local method stack.
How the garbage collector determines which objects to recycle---in-depth understanding of Java virtual machines