Java G1 垃圾收集器开启字符串去重

Java GC JVM About 2,482 words

字符串去重

不是对字符串常量池进行去重,因为StringTable本来就是不重复的。

这里的去重,去的是String对象中的char[]byte[](不同JDK版本,对应不同实现)。

判断标准

string1.equals(string2)=true

参数

UseStringDeduplication:使用字符串去重。

StringDeduplicationAgeThreshold:达到指定年龄的字符串去重。

PrintStringDeduplicationStatistics:打印字符串去重统计信息。(OpenJDK 11中无此标志位)

说明

只适用于G1垃圾收集器。

示例

基于Java8,因为Java11没有了PrintStringDeduplicationStatistics标志位,看不到演示效果。

/**
 * Java8
 * -XX:+UseG1GC -XX:+UseStringDeduplication -XX:StringDeduplicationAgeThreshold=1 -XX:+PrintStringDeduplicationStatistics
 *
 * Java11: 默认是 G1GC,PrintStringDeduplicationStatistics 无此 flag
 * -XX:+UseStringDeduplication -XX:StringDeduplicationAgeThreshold=1
 */
public class StringDeduplicateInG1Demo {
    public static void main(String[] args) {
        String s1 = new String("hello world");
        String s2 = new String("hello world");
        System.gc();
    }
}

输出:

[GC concurrent-string-deduplication, 59.1K->46.6K(12.5K), avg 21.1%, 0.0003023 secs]
   [Last Exec: 0.0003023 secs, Idle: 0.0000039 secs, Blocked: 0/0.0000000 secs]
      [Inspected:            1803]
         [Skipped:              0(  0.0%)]
         [Hashed:             614( 34.1%)]
         [Known:              858( 47.6%)]
         [New:                945( 52.4%)     59.1K]
      [Deduplicated:          157( 16.6%)     12.5K( 21.1%)]
         [Young:                0(  0.0%)      0.0B(  0.0%)]
         [Old:                157(100.0%)     12.5K(100.0%)]
   [Total Exec: 1/0.0003023 secs, Idle: 1/0.0000039 secs, Blocked: 0/0.0000000 secs]
      [Inspected:            1803]
         [Skipped:              0(  0.0%)]
         [Hashed:             614( 34.1%)]
         [Known:              858( 47.6%)]
         [New:                945( 52.4%)     59.1K]
      [Deduplicated:          157( 16.6%)     12.5K( 21.1%)]
         [Young:                0(  0.0%)      0.0B(  0.0%)]
         [Old:                157(100.0%)     12.5K(100.0%)]
   [Table]
      [Memory Usage: 23.9K]
      [Size: 1024, Min: 1024, Max: 16777216]
      [Entries: 1696, Load: 165.6%, Cached: 0, Added: 1711, Removed: 15]
      [Resize Count: 0, Shrink Threshold: 682(66.7%), Grow Threshold: 2048(200.0%)]
      [Rehash Count: 0, Rehash Threshold: 120, Hash Seed: 0x0]
      [Age Threshold: 1]
   [Queue]
      [Dropped: 0]

解读

执行了1次,耗时0.0003023秒。

[Total Exec: 1/0.0003023 secs, Idle: 1/0.0000039 secs, Blocked: 0/0.0000000 secs]

去重了12.5k大小的字符串。

[Deduplicated:          157( 16.6%)     12.5K( 21.1%)]

文档

实现原理可参见文档。

https://openjdk.java.net/jeps/192

Views: 2,804 · Posted: 2021-08-18

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh