This is the 29th day of my participation in the August Wenwen Challenge.More challenges in August

1. Introduction

At present, the current virtual machine mainly adopts four garbage collection algorithms, which are mark-clear algorithm, mark-copy inversion algorithm and mark-collation algorithm. In order to improve the efficiency of memory collection, the VIRTUAL machine divides the JVM into different regions and adopts different garbage collection algorithms for different regions, which is the idea of generational collection algorithm.

This paper mainly introduces three collection algorithms


2. Mark-clear algorithm

The algorithm is divided into two stages, marking all objects that need to be recycled, and recycling is unified after the marking. This algorithm is very easy to understand, is very simple, the following algorithm is based on the algorithm to improve the basis.

The disadvantage is that the efficiency of marking and clearing is relatively low. And this can cause a lot of fragmentation in memory. As a result, if we need to use a large chunk of memory, such as when a large object comes in, we cannot allocate enough contiguous memory.


3. Mark-copy algorithm

In order to solve the efficiency problem, “mark-copy” collection algorithm appeared; It splits the memory module into two parts and uses only one of them anyway.

When the used area of memory is nearly full, the remaining objects are marked and moved to another area that is not used. The entire area is cleared again, i.e., half of the area is reclaimed each time.

Although the mark-copy algorithm solves the problem of memory fragmentation, it also brings the problem of memory shrinkage and low space utilization


3. Mark-tidy algorithm

A marking algorithm based on the characteristics of the old era, the marking process is still the same as the “mark-clean” algorithm, but the next step is not to directly reclaim the recyclable objects, but to move all surviving objects to one end, and then directly clean up the memory beyond the end boundary

For the old age, the object survival rate is high, and there is no other memory allocation guarantee, so the mark-copy algorithm cannot be used in the old age.


4. Generational collection algorithm

In order to allocate memory faster and better, most current JVMS use a generational collection algorithm. This is not a new algorithm, but rather the JVM’s memory region is divided into several regions with different characteristics, and different garbage collection algorithms are used for these different regions.

For example, in the new generation, a large number of objects die in each collection, so a “mark-copy” algorithm can be used to complete each garbage collection for a small amount of object copying cost. Older objects have a higher chance of survival, and there is no extra space for allocation guarantees, so we must choose the “mark-clean” or “mark-clean” algorithm for garbage collection.