Explore the JVM - garbage collection (b)

1. garbage collection algorithm

1.1 Clear mark (Mark-Sweep) algorithm

Mark - sweep algorithm is the first use and better system of garbage collection algorithm, subsequent collection algorithms are based on their design ideas and make improvements to its insufficient obtained.

The algorithm is divided into "mark" and "clear" in two stages:

  • First all the objects need to be recovered, which marks the validity determination target process is, during the execution of reachability analysis;
  • After marking the completion of the unity of all the objects are marked recovery.

It has two main problems:

  • One is efficiency, marking and removal efficiency of both processes is not high;
  • Another problem is space, will generate a lot of discrete memory fragmentation mark after clearing space debris could cause too much time in the future need to allocate large objects in the program is running, you can not find enough contiguous memory in advance and had to trigger another garbage collection action.

    

1.2 Copy (Copying) algorithm

By employing dual zone replication algorithm used interchangeably in this way to solve the mark - sweep algorithm with low efficiency. It may be an equivalent amount of available memory is divided into two areas (free areas and area use), uses only one. When the area is being used needs to be garbage collection, live objects are copied to another block area. Areas that had previously been used is reset, into an empty area. This allows each recovered memory is the memory of half the interval for recycling.

The cost of this algorithm are:

In order to reduce the memory half, lower utilization of space.

Based on the above defects of the copy algorithm can be divided into a large memory space and Eden Survivor two smaller spaces, and wherein each use a Survivor Eden. When recycling, the Eden and Survivor also alive objects once copied to another piece of Survivor space, and finally clean out Survivor Eden and just used space. HotSpot VM Eden and Survivor default size ratio is 8: 1, i.e. each new generation the available memory space for the new generation of 90% of the whole capacity (80% + 10%), only 10% of the memory is "wasted . "

   

3. Mark - finishing (Mark-Compact) algorithm

复制收集算法在对象存活率较高时就要进行较多的复制操作,效率将会变低。更关键的是,如果不想浪费50%的空间,就需要有额外的空间进行分配担保,以应对被使用的内存中所有对象都100%存活的极端情况,所以在老年代一般不能直接选用这种算法。

所以根据老年代的特点提出的一种标记算法,标记过程仍然与“标记-清除”算法一样,但后续步骤不是直接对可回收对象回收,而是让所有存活的对象向一端移动,然后直接清理掉端边界以外的内存。

 

 

1.4 分代收集(Generational Collection)算法

当前商业虚拟机的垃圾收集都采用“分代收集”(Generational Collection)算法,这种算法并没有什么新的思想,只是根据对象存活周期的不同将内存划分为几块。

一般是把Java堆分为新生代和老年代,这样就可以根据各个年代的特点采用最适当的收集算法。

  • 在新生代中,每次垃圾收集时都发现有大批对象死去,只有少量存活,那就选用复制算法,只需要付出少量存活对象的复制成本就可以完成收集。
  • 在老年代中因为对象存活率高、没有额外空间对它进行分配担保,就必须使用“标记—清理”或者“标记—整理”算法来进行回收。

2. 垃圾收集器

如果说收集算法是内存回收的方法论,那么垃圾收集器就是内存回收的具体实现。

2.1 Serial收集器

 

Guess you like

Origin www.cnblogs.com/zjfjava/p/11838480.html