JVM 字符串常量池中的垃圾回收

Java JVM About 2,253 words

字符串常量池

字符串常量池也存在垃圾回收,当Full GC时,垃圾收集器同样会收集常量池中的String常量字符串。

示例

添加-XX:+PrintStringTableStatistics打印StringTable的统计信息。

创建100个字符串。

/**
 * -XX:+PrintStringTableStatistics -XX:+PrintGCDetails
 */
public class StringTableStatDemo {

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            ("aaa" + i).intern();
        }
    }
}

输出:

StringTable statistics:
Number of buckets       :      1009 =      4036 bytes, avg   4.000
Number of entries       :       971 =     11652 bytes, avg  12.000
Number of literals      :       971 =     50992 bytes, avg  52.515
Total footprint         :           =     66680 bytes
Average bucket size     :     0.962
Variance of bucket size :     0.902
Std. dev. of bucket size:     0.950
Maximum bucket size     :         5

创建10000个字符串。

/**
 * -XX:+PrintStringTableStatistics -XX:+PrintGCDetails
 */
public class StringTableStatDemo {

    public static void main(String[] args) {
        for (int i = 0; i < 10000; i++) {
            ("aaa" + i).intern();
        }
    }
}

输出:

StringTable statistics:
Number of buckets       :      1009 =      4036 bytes, avg   4.000
Number of entries       :     10910 =    130920 bytes, avg  12.000
Number of literals      :     10910 =    521008 bytes, avg  47.755
Total footprint         :           =    655964 bytes
Average bucket size     :    10.813
Variance of bucket size :     4.753
Std. dev. of bucket size:     2.180
Maximum bucket size     :        19

创建1000000个字符串。

/**
 * -XX:+PrintStringTableStatistics -XX:+PrintGCDetails
 */
public class StringTableStatDemo {

    public static void main(String[] args) {
        for (int i = 0; i < 1000000; i++) {
            ("aaa" + i).intern();
        }
    }
}

输出:

StringTable statistics:
Number of buckets       :      1009 =      4036 bytes, avg   4.000
Number of entries       :     46405 =    556860 bytes, avg  12.000
Number of literals      :     46405 =   2232632 bytes, avg  48.112
Total footprint         :           =   2793528 bytes
Average bucket size     :    45.991
Variance of bucket size :    29.107
Std. dev. of bucket size:     5.395
Maximum bucket size     :        57

现象

统计信息中的Number of entriesNumber of literals表示字符串的数量,当创建过多的字符串发生Full GC后,字符串常量池中的字符串也被回收了一部分。

Views: 4,239 · Posted: 2021-08-17

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

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

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


Today On History
Browsing Refresh