The process of garbage collection consists of two parts: Finding the Dead object, and removing the dead object.
There are two ways to determine which objects survive: The reference counting algorithm, the accessibility analysis algorithm.
Scenario One: Reference counting algorithm
Add a reference counter to the object, the counter value is incremented by 1 whenever there is a reference to it, and when the reference fails, the counter value is reduced by 1, and the value of the counter is 0 o'clock indicating that the object is dead (can be recycled).
Advantages: Simple to achieve, high efficiency of judgement.
Cons: Difficult to solve the problem of referencing each other between objects.
such as: Objects Obja and OBJB have field instance, Obja.instance=objb,objb.instance=obja; Besides, Obja and OBJB have no other references, theoretically obja and OBJB can be recycled (inaccessible) , but because the counter becomes 0, it causes a memory leak.
Scenario Two: Accessibility analysis algorithm
The "GC Roots" object is used as the starting point, starting from these nodes to search down, the object marked to be searched, the objects in the heap that are not maked indicate unreachable (can be recycled).
In the Java language, classes as GC roots include the following four types of objects:
1. Objects referenced in the virtual machine stack (local variable table in the stack frame)
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 (that is, generally referred to as the native method) in the local method stack
Garbage collection algorithm:
1. Mark-Clear (Mark-sweep): Use the method described above to mark the objects that need to be recycled, and then uniformly reclaim all tagged objects after tagging.
2. Replication algorithm: In order to solve the problem of free space fragmentation caused by the above algorithm cleanup, the replication algorithm divides the memory space into two equal-sized parts, and when part is finished, moves the surviving object to another part.
3. Labeling-Finishing (mark-compact): The above algorithm causes the actual use of space to occupy only half of the allocated space, marking-sorting algorithm after the tag, all the surviving objects moved to one end, and then directly clean out the memory outside the end of the boundary.
4. Generational collection algorithm: The study shows that object 98% in the Cenozoic is "dying in the face of death", so the object is added to the age attribute, depending on the age to determine the location of the object. For specific reference :java garbage collection
Description: The contents of this article refer to the book deep understanding of Java Virtual Machines (2nd edition) "
Introduction to garbage collection algorithms--JVM reading notes < two >