This is the 16th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021″
preface
JVM – Initial garbage Collection – Nuggets (juejin. Cn)
This article explained how to determine if an object is garbage, but recycling requires some algorithms.
There are four common recycling algorithms: 1. Mark clearing algorithm; 2. Mark collation algorithm; 3.
Mark clearing algorithm
The tag sweep algorithm is one of the earliest and most basic garbage collection algorithms, introduced in 1960 by John McCarthy, the father of Lisp.
The algorithm can be divided into two stages: 1, mark 2, clear
tag
Objects that we believe are not associated with GC ROOT are marked as garbage.
remove
Free up the memory of the object we just marked and put it in the free memory list, from which we can use it the next time we need to create an object.
summary
This algorithm is the most basic collection algorithm, and many subsequent collection algorithms are based on this algorithm and improve the shortcomings of the algorithm. It mainly has the following two disadvantages:
1. The execution efficiency is extremely unstable. When there are a large number of objects in the heap that need to be reclaimed, a large number of marking and clearing operations need to be done. 2. Fragmentation of memory space. After marking and clearing operations, a large number of discontinuous memory fragments will be generated.
Tag sorting algorithm
The algorithm can be divided into two stages: 1
tag
This stage is the same as the first stage of the marker clearing algorithm.
finishing
The phase is mainly to solve the problem of memory space fragmentation caused by the marker cleaning algorithm, and tidy up the memory when cleaning garbage.
summary
In the process of label sorting algorithm, memory movement of objects is involved, which is bound to be relatively low efficiency.
Mark copy algorithm
In order to solve the problem of low efficiency when a large number of objects need to be reclaimed, the tag copy algorithm divides the available memory into two pieces of equal size according to the capacity, and only one of them is used each time. When this area of memory is used up, the surviving objects are copied to the other area, and the used memory space is cleaned up again.
tag
As with the tag cleanup algorithm, objects that are not associated with the GC ROOT are marked as garbage.
Copy the recycling
Copy objects that do not need to be collected to another part of the free memory, then the previous chunk of memory is garbage, empty the entire previous chunk, and then swap places, the next time to do the same operation.