What is garbage?
In Java, it is associated with an object by reference, that is, if you want to manipulate the object, you must do so by reference.
An object that loses a referential relationship, called a garbage object.
Garbage collection algorithm
1. Reference counting method
According to the definition of "garbage", the intuitive approach is to set a reference counter for each object. When you scan an object, it is considered garbage if its reference is 0, and you are ready to recycle.
However, the disadvantage of this is that there is no way to eliminate garbage objects that are circular references, such as:
public class Main {public static void main (string[] args) {MyObject object1 = new MyObject (); MyObject object2 = new MyObject (); Object1.object = Object2; Object2.object = Object1; Object1 = null; Object2 = null; }} class myobject{public object object = NULL;}
Although the references to Object1 and Object2 are eliminated, the reference count is not 0 because they still point to each other, so they are not recycled. In order to solve this problem, there is a second approach, the accessibility analysis method.
2. Accessibility Analysis method
The basic idea of this method is to search by a series of "GC Roots" objects as a starting point, if there is no unreachable path between "GC Roots" and an object, it is said that the object is unreachable, but it is important to note that objects that are judged to be unreachable do not necessarily become recyclable objects. An object that is judged unreachable must undergo at least two marking processes to become a recoverable object, and if it is still not possible to escape from being a recyclable object during these two marks, it is essentially a recyclable object.
Garbage collection mechanism in Java