This paper will use the method of elimination to explain the new generation of regional division, so that readers can more clearly understand the principle of generational collector, before we start to understand the overall generational collector.

The generational collector will divide the memory space into two regions: old generation and new generation, and the new generation will be divided into Eden region and two Survivor regions (From Survivor and To Survivor). The memory space distribution diagram is shown as follows:

(image by fancydeepin)

You can see that the default ratio of Eden and Survivor partitions is 8:1:1. This value can be set using: -xx :SurvivorRatio. The default value is: -xx :SurvivorRatio=8.

By the way, the default memory ratio of the new generation and the old generation is 1:2, which can be set by: -xx :NewRatio.

Why can’t there be zero Survivor partitions?

If Survivor is 0, that is, there is only one Eden partition in the new generation. After each garbage collection, the surviving objects will enter the old generation, so that the memory space of the old generation will be filled up quickly, triggering the most time-consuming Full GC. Obviously, the efficiency of such a collector is totally unacceptable.

Why can’t there be 1 Survivor partition?

If there is one Survivor partition, and if we divide the two regions 1:1, then half of the memory space is idle at any given time, obviously too little space utilization is not the best solution.

But if you set the ratio of memory space to 8:2, it just seems “fine”, assume that the new generation of memory is 100 MB (Survivor size is 20 MB), and now after 70 MB objects are garbage collected, the remaining active objects are 15 MB into Survivor. At this point, the new generation is down to 5 MB of available memory, which quickly leads to garbage collection. Obviously, the biggest problem with this garbage collector is that it requires frequent garbage collection.

Why are there 2 Survivor partitions?

If the Survivor partition has two partitions, we can set the memory ratio of Eden, From Survivor, and To Survivor To 8:1:1, so that the new generation memory utilization is 90% at any time, which is basically as expected. In addition, most objects of the virtual machine are in line with the “instant death” feature, so every new object is generated in Eden area with a large space proportion. After garbage collection, the surviving object method is stored in Survivor area. If it is the surviving object in Survivor area, the “age” is +1. When age reaches 15 (set by -xx :+MaxTenuringThreshold) the object is upgraded to the old generation.

conclusion

According to the above analysis, when there are two Survivor partitions of the new generation, both the space utilization rate and the efficiency of program running are optimal, so this is also the reason why there are two Survivor partitions.