The Garbage-First (G1) collector is a server-style garbage collector, targeted for multi-processor machines with large memories. It meets garbage collection (GC) pause time goals with a high probability, while achieving high throughput. The G1 garbage collector is fully supported in Oracle JDK 7 update 4 and later releases. The G1 collector is designed for applications that: - Can operate concurrently with applications threads like the CMS collector. - Compact free space without lengthy GC induced pause times. - Need more predictable GC pause durations. - Do not want to sacrifice a lot of throughput performance. - Do not require a much larger Java heap. G1 is planned as the long term replacement for the Concurrent Mark-Sweep Collector (CMS). Comparing G1 with CMS, there are differences that make G1 a better solution. One difference is that G1 is a compacting collector. G1 compacts sufficiently to completely avoid the use of fine-grained free lists for allocation, and instead relies on regions. This considerably simplifies parts of the collector, and mostly eliminates potential fragmentation issues. Also, G1 offers more predictable garbage collection pauses than the CMS collector, and allows users to specify desired pause targets.
Recommended Use Cases for G1
The first focus of G1 is to provide a solution for users running applications that require large heaps with limited GC latency. This means heap sizes of around 6GB or larger, and stable and predictable pause time below 0.5 seconds.
Applications running today with either the CMS or the ParallelOldGC garbage collector would benefit switching to G1 if the application has one or more of the following traits.
- Full GC durations are too long or too frequent.
- The rate of object allocation rate or promotion varies significantly.
- Undesired long garbage collection or compaction pauses (longer than 0.5 to 1 second)
Note: If you are using CMS or ParallelOldGC and your application is not experiencing long garbage collection pauses, it is fine to stay with your current collector. Changing to the G1 collector is not a requirement for using the latest JDK.
G1
- G1在压缩空间方面有优势
- G1通过将内存分成区域(Region)的方式防止内存碎片化问题
- Eden,Surivior,Old区域不再固定,在内存使用效率上来说更灵活
- G1可以设置预期停顿时间(Pause Time)来控制垃圾收集,避免应用雪崩
- G1在回收内存后会马上同事做合合并空闲内存的工作,而CMS默认是在STW(Stop the world)的时候来做
- G1会在Young GC中使用,而CMS只能在O区使用
就目前而言,CMS还是默认首选的GC策略,可能在以下场景G1更合适
- 服务端多核CPU,JVM内存占用较大的应用(至少4G)
- 应用在内存中会产生大量内存碎片,需要经常压缩空间
- 想要更可控,更预期的GC停顿时间;防止高并发下应用雪崩现象
-XX:+UseG1GC
-XX:MaxGCPauseMillis=100
-XX:+ParallelRefProcEnabled
-XX:-ResizePLAB
-XX:ParallelGCThreads=28
-XX:+UseG1GC
-XX:MaxGCPauseMillis=500
-XX:+ParallelRefProcEnabled
-XX:-ResizePLAB
-XX:ParallelGCThreads=8
-Xloggc:/pdata/log/hbase/gc/gc-%t.log
-XX:+PrintGCDetails
-XX:+PrintGCTimeStamps
-XX:+PrintGCCause
-XX:+PrintTenuringDistribution
-XX:+UseGCLogFileRotation
-XX:NumberOfGCLogFiles=10
-XX:GCLogFileSize=5M