This paper mainly introduces the garbage collection algorithm of Java Virtual machine.
I. Overview
second, mark-Clear algorithm
Mark-sweep. Like a name, the algorithm is divided into two steps:
- Tags: objects that need to be recycled at the mark
- Clear: The Tagged object is reclaimed uniformly after the tag is complete.
Disadvantages:
- Efficiency issues: The efficiency of labeling and purging is not high
- Space problem: A large number of discontinuous memory fragments are generated after the tag is cleared
third, the replication algorithm
The replication algorithm is an optimization of the tag cleanup, which divides the memory on the heap into two equal-sized areas, one for the idle area and one for the active area. In the program run, the actual use of the active area, that is, 50% of the space is wasted
Implementation process:
- Find all the surviving objects in the active space.
- Copy these surviving objects to an idle area.
- The previous activity space is emptied and then becomes free space, and the area where the surviving object resides becomes the active space.
Advantage, after the memory is collected, there is a large amount of contiguous free space.
Disadvantage, 50% of the memory space is placed, only in the event of memory recycling, the GC will borrow the idle area to achieve memory recovery work.
Iv. marking-finishing algorithm
The tag action is consistent with the tag-purge algorithm, and subsequent operations do not just clean the object directly, but instead let all surviving objects move toward one end after cleaning up the useless objects and update the pointers that reference their objects.
The main drawback: on the basis of tag-purge, the object movement is relatively expensive, and the benefit is that it will not produce memory fragmentation.
five, generation of collection algorithm
Divide the Java heap into the new generation and the old age:
- New belt: Each time there will be a large number of objects die, only a small number of survival, select the replication algorithm, only a small number of surviving objects to replicate, replication cost is low.
- Old age: The old age has a high survival rate and is recycled using the mark-sweep or tag-grooming algorithm.
Java Virtual machine-garbage collection algorithm