进学阁

业精于勤荒于嬉,行成于思毁于随

0%

10 StringTable

1 String的基本概念

使用概览

  • String属于引用数据类型,不像C#有string关键字,Java没有对应的string关键字。
  • String 声明为 final 的,不可被继承。
  • String 实现了 Serializable 接口:表示字符串是支持序列化的。
  • String 实现了 Comparable 接口:表示 String 可以比较大小
  • 【重要变更】String的内部定义:String在JDK8及以前内部定义了<font style="color:#F5222D;">final char[] value</font>用来存储字符串数据。JDK9版本开始后更改为了<font style="color:#F5222D;">byte[]+编码标记</font>。同时,StringBuffer和StringBuilder也相应的更改了。更改原因:大部分数据都在1个字节内(byte为1个字节,char为2个字节),节省空间考虑。官网地址:JEP 254: Compact Strings (java.net)

参考文档:

Java常用类.pdf · 资料文件 · 语雀

String的不可变更性

String不可变性的几个体现:

  1. 当对字符串重新赋值时,会更改该变量栈空间上存储的地址值,原栈空间指向的实际值未做更改。
  2. 当对字符串进行连接操作时,会更改该变量栈空间上存储的地址值,原栈空间指向的实际值未做更改。
  3. 当调用String的replace()方法修改字符或字符串, 也会更改该变量栈空间上存储的地址值,原栈

间指向的实际值未做更改。

1
2
3
4
String str = "abc";
String str2 = str.replace('a', '1');
System.out.println(str);//abc//str本身未做改变
System.out.println(str2);//1bc

2 String的常用操作

String的常用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1 String方法都不能更改原来的String值。因为其内部是final char[]或final byte[],必须以新的变量去接收更改后的值。
如:toLowerCase()/toUpperCase()/trim()/replace()。

2. 截取的方法(substring)为左闭右开
String substring(int beginIndex, int endIndex)。返回一个新字符串,它是此字符串从beginIndex(包含)开始截取到endIndex(不包含)的一个子字符串。

3. 除非指定了ignoreCase,否则String方法内部都是大小写敏感的。
equasl()/endsWith()/startWith()/contains()内部都是大写敏感的。手动指定了忽略了大小写的方法的除外,如:equalsIgnoreCase()。

4. 拼接方法:String concat(String str)等价于“+”拼接。

5. String与char[]之间的转换
String->char[]:调用String.toCharArray()方法,如char[] arrs = s1.toCharArray();
char[]->String:调用String的构造器,如String str = new String(arrs);

6. isEmpty()是否0长度的字符串
字符串通过 length() 方法计算字符串长度,如果返回 0,isEmpty()即为true

String.format方法的使用

1
2
3
4
String str=String.format("Hi,%s:%s.%s", "王南","王力","王张");
System.out.println(str);

//打印输出的值为:Hi,王南:王力.王张

参考文档

String的编码问题

String和byte[]之间的转换

  1. **String->byte[]**:调用String.getBytes(),如_byte[] bytes = s1.getBytes();_
  2. byte[]->String:调用String的构造器,如_String str = byte bytes[]_

注意点:编码(->byte[])和解码(->String)的格式必须一致。只有to byte和byte from才需要特别注意。

3 String创建对象和其内存分布

3.1 String的内存原理

浅堆

浅堆是指一个对象所消耗的内存。在 64 位系统中,一个对象引用会占据 4 个字节,一个 int 类型会占据 4 个字节,long 型变量会占据 8 个字节,每个对象头需要占用 8 个字节。根据堆快照格式不同,对象的大小可能会同 8 字节进行对齐。具体可详见:

补充:浅堆深堆与内存泄露


计算String对象的大小

  • 如果String作为对象:通过String str=new String("你好");String str="你好"的方式创建String对象:共计24bytes(24个字节)。

  • 如果String变为变量:4bytes(4个字节)

StringPool字符串常量池

在Java语言中有 8 种基本数据类型和一种比较特殊的类型 String。这些类型为了使它们在运行过程中速度更快、更节省内存,都提供了一种常量池的概念。

常量池就类似一个 Java 系统级别提供的缓存。8种基本数据类型的常量池都是系统协调的,String的常量池比较特殊,它会根据String类的使用而调用。

String 的 String Pool 是一个固定大小的 Hashtable,默认值大小长度是 1009。如果放进 String Pool 的 String 非常多,就会造成 Hash 冲突严重,从而导致链表会很长,而链表长了后直接会造成的影响就是当调用 String.intern 时性能会大幅下降。字符串常量池不会存储相同内容的字符串。

使用-XX:StringTablesize可设置 StringTable 的长度

  • 在 jdk6 中 StringTable 是固定的,就是 1009 的长度,所以如果常量池中的字符串过多就会导致效率下降很快。StringTablesize 设置没有要求
  • 在 jdk7 中,StringTable 的长度默认值是 60013,StringTablesize 设置没有要求
  • 在 JDK8 中,设置 StringTable 长度的话,1009 是可以设置的最小值

StringPool常量池的使用

它的主要使用方法有两种:

  • 直接使用双引号声明出来的 String 对象会直接存储在常量池中。
  • 如果不是用双引号声明的 String 对象,可以使用 String 提供的 intern()方法。这个后面重点谈。

StringPool常量池存储在哪?

  • Java 6 及以前,字符串常量池存放在永久代。
  • Java 7,字符串池的逻辑做了很大的改变,即将字符串常量池的位置调整到 Java 堆内。
    • 所有的字符串都保存在堆(Heap)中,和其他普通对象一样,这样可以让你在进行调优应用时仅需要调整堆大小就可以了。
    • 字符串常量池概念原本使用得比较多,但是这个改动使得我们有足够的理由让我们重新考虑在 Java 7 中使用String.intern()
  • Java8,字符串常量池在方法区的元空间上。

Java7为什么要调整StringTable的存储位置?

原因:1、永久代的perSize默认比较小;2、永久代垃圾回收频率低

附官网地址:Java SE 7 Features and Enhancements (oracle.com)

Synopsis: In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.

简介:在 JDK 7 中,内部字符串不再分配在 Java 堆的永久代中,而是分配在 Java 堆的主要部分(称为年轻代和老年代),与应用程序创建的其他对象一起。这种变化将导致更多的数据驻留在主 Java 堆中,而更少的数据在永久代中,因此可能需要调整堆的大小。大多数应用程序将看到由于这一变化而导致的堆使用的相对较小的差异,但加载许多类或大量使用 String.intern()方法的大型应用程序将看到更明显的差异。

3.2 通过字面量的方式

格式:String str = “FlyShow”;

生成的对象:栈空间str、str指向的字符串常量区

原理分析:如图

3.3 通过String.intern()方法

通览

格式:String str = new String("FlyShow").intern();

生成的对象:栈空间str、new的时候在堆空间生成的String对象Flyshow、调用intern()方法后去常量池查找如果没有就开辟的常量池字符串对象Flyshow。

方法说明:通过new String()在堆空间开辟了对象,然后调用intern()方法后会判断字符串常量池中是否存在”FlyShow”值,如果存在则返回常量池中该对象的地址。如果不存在JDK6的情况是在常量池中先复制堆上的”FlyShow”到常量池并再返回该对象在常量池的地址给变量str,在JDK7及以后,字符串常量池复制的是堆空间的一个引用,而不再复制完整内容,返回的也是这个堆空间的地址。

intern方法可以确保字符串在内存里只有一份拷贝,这样可以节约内存空间,加快字符串操作任务的执行速度。注意,这个值会被存放在字符串内部池(String Intern Pool)。

调用intern()方法在不同JDK版本下的区分

JDK1.6 中,将这个字符串对象尝试放入串池。

  • 如果字符串常量池中有,则并不会放入。返回已有的字符串常量池中的对象的地址。
  • 如果没有,会把此对象复制一份,放入串池,并返回串池中的对象地址。

JDK1.7起,将这个字符串对象尝试放入串池。

  • 如果串池中有,则并不会放入。返回已有的串池中的对象的地址
  • 如果没有,则会把对象的引用地址复制一份,放入串池,并返回串池中的引用地址(此时返回的就是对象的引用)

进一步了解

官方 API 文档中的解释

public String intern()

Returns a canonical representation for the string object.

A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the [equals(Object)](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#equals-java.lang.Object-) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.


Returns:
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

当调用 intern 方法时,如果池子里已经包含了一个与这个 String 对象相等的字符串,正如 equals(Object)方法所确定的,那么池子里的字符串会被返回。否则,这个 String 对象被添加到池中,并返回这个 String 对象的引用。

由此可见,对于任何两个字符串 s 和 t,当且仅当 s.equals(t)为真时,s.intern() == t.intern()为真。

所有字面字符串和以字符串为值的常量表达式都是 interned。

返回一个与此字符串内容相同的字符串,但保证是来自一个唯一的字符串池。

intern 是一个 native 方法,调用的是底层 C 的方法

1
2
3
4
5
6
7
8
public native String intern();

//如果不是用双引号声明的 String 对象,可以使用 String 提供的 intern 方法,它会从字符串常量池中查询当前字符串是否存在,若不存在就会将当前字符串放入常量池中。
String myInfo = new string("I LOVE YOU").intern();

//也就是说,如果在任意字符串上调用 String.intern 方法,那么其返回结果所指向的那个类实例,必须和直接以常量形式出现的字符串实例完全相同。
//因此,下列表达式的值必定是 true
("a"+"b"+"c").intern() == "abc"

通俗点讲,Interned string 就是确保字符串在内存里只有一份拷贝,这样可以节约内存空间,加快字符串操作任务的执行速度。注意,这个值会被存放在字符串内部池(String Intern Pool)


intern 的使用:JDK6 vs JDK7/8

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//案例1
String s = new String("1");//创建了两个对象:堆空间中一个new对象;字符串常量池中一个字符串常量"1"(注意:此时字符串常量池中已有"1")
s.intern();//由于字符串常量池中已存在"1"
String s2 = "1";//由于字符串常量池中已存在"1"
System.out.println(s==s2); //s指向的是堆空间中的对象地址;s2指向的是堆空间中常量池中"1"的地址。所以不相等
//结果
jdk1.6 false
jdk7/8 false

//案例2
String s3 = new String("1") + new String("1");//等价于new String("11"),但是,常量池中并不生成字符串"11"
s3.intern();//由于此时常量池中并无"11",jdk7/8是把s3中记录的对象的地址存入常量池;jdk6是直接复制的内容到常量池。
String s4 = "11";
System.out.println(s3==s4);
//结果
jdk1.6 false
jdk7/8 true

intern的效率测试

我们通过测试一下,使用了 intern 和不使用的时候,其实相差还挺多的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class ClassTest throws InterruptedException{
static final int MAX_COUNT = 1000 * 10000;
static final String[] arr = new String[MAX_COUNT];
static final String a="xcxx";

public static void main(String[] args) {
Integer [] data = new Integer[]{1,2,3,4,5,6,7,8,9,10};
long start = System.currentTimeMillis();
for (int i = 0; i < MAX_COUNT; i++) {
//arr[i] = new String(String.valueOf(data[i%data.length])).intern();//花费的时间为:925
//arr[i] = new String(String.valueOf(data[i%data.length]));//花费的时间为:2423

//new String(String.valueOf(data[i%data.length]));//花费的时间为:236
//new String(String.valueOf(data[i%data.length])).intern();//花费的时间为:844
}
long end = System.currentTimeMillis();
System.out.println("花费的时间为:" + (end - start));

Thread.sleep(10000);
}
}

Q:为什么在量大且很多重复字符串的时候使用arr[i] = new String(String.valueOf(data[i%data.length]))性能比new String(String.valueOf(data[i%data.length])).intern()差?

A:主要是在空间消耗上,不加intern,内存里的对象都在Heap上,占据了大量的内存空间。使用了intern,堆里面的空间会被GC(new String这一步还是会在堆上面创建对象的),重复的变量都在StringPool上了,空间会大幅降低,对应的时间消耗就变小了。

图示内存实例数:上一个是不加intern,下一个是加了intern。

结论:对于程序中大量使用存在的字符串时,尤其存在很多已经重复的字符串时,使用 intern()方法能够节省内存空间。

大的网站平台,需要内存中存储大量的字符串。比如社交网站,很多人都存储:北京市、海淀区等信息。这时候如果字符串都调用 intern()方法,就会很明显降低内存的大小。

3.4 通过拼接:全常量拼接

  • 常量与常量的拼接结果在常量池(如果变量使用final修饰也认为是常量),原理是编译期优化
  • 使用 final 修饰,即为常量。会在编译器进行代码优化。在实际开发中,能够使用 final 的,尽量使用。
  • 常量池中不会存在相同内容的变量。
  • 如果拼接的结果调用 intern()方法,则主动将常量池中还没有的字符串对象放入池中,并返回此对象地址
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//案例1
使用格式
String str = "a" + "b" + "c";

final String s1="a";
String str = s1 + "b";

生成的对象:栈空间str、str指向的字符串常量区。
原理分析:常量与常量的拼接结果在常量池,原理是编译期优化,其内存布局和通过字面量方式生成的是一致。
note:常量池中不会存在相同内容的常量。

//案例2
String s1 = "a" + "b" + "c";//s1指向的对象存在字符串常量区
String s2 = "abc";//s1指向的对象存在字符串常量区
System.out.println(s1 == s2);//值为true
原因分析:编译器将.java文件编译成.class文件时,语句String s1 = "a" + "b" + "c";自动编译成了String s1 = "abc";

3.4+ 通过拼接:变量拼接

  • 拼接多方只要其中有一个是变量,结果就在堆中。变量拼接的原理是 StringBuilder。
  • 不使用 final 修饰,即为变量。如下面例子s3 行的 s1 和 s2,会通过 new StringBuilder 进行拼接
1
2
3
4
5
6
7
8
9
10
11
//案例
String s1 = "a";
String s2 = "b";
String s3 = s1 + s2;//编译后约等于String s3 = new StringBuiler().append("a").append("b").toString();
其中oString()=>new String(char value[], int offset, int count)

内存分析:栈空间str/s1/s2、StringBuilder堆对象、s1/s2的字符串常量区、str指向的最终的堆结果之,注意:str的值未在字符串常量区里。

原理分析:拼接运算中只要其中有一个是变量值(非final修饰的变量),则结果就相当于在堆中(非字符串常量池里) new String(char value[], int offset, int count)开辟了新对象。
如上语句在JDK5.0之后反编译后看到的内部逻辑为(JDK<5.0则将StringBuiler替换成StringBuffer):
String s3 = new StringBuiler().append("a").append("b").toString();其中StringBuilder.toString()=>new String(char value[], int offset, int count);

字符串拼接性能对比

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class Test
{
public static void main(String[] args) {
int times = 50000;

// String
long start = System.currentTimeMillis();
testString(times);
long end = System.currentTimeMillis();
System.out.println("String: " + (end-start) + "ms");

// StringBuilder
start = System.currentTimeMillis();
testStringBuilder(times);
end = System.currentTimeMillis();
System.out.println("StringBuilder: " + (end-start) + "ms");

// StringBuffer
start = System.currentTimeMillis();
testStringBuffer(times);
end = System.currentTimeMillis();
System.out.println("StringBuffer: " + (end-start) + "ms");
}

public static void testString(int times) {
String str = "";
for (int i = 0; i < times; i++) {
str += "test";
}
}

public static void testStringBuilder(int times) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++) {
sb.append("test");
}
}

public static void testStringBuffer(int times) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < times; i++) {
sb.append("test");
}
}
}

// 结果
String: 7963ms
StringBuilder: 1ms
StringBuffer: 4ms

本实验进行 5 万次循环,String 拼接方式的时间是 StringBuilder.append 方式的约 8000 倍,StringBuffer.append()方式的时间是 StringBuilder.append()方式的约 4 倍

可以看到,通过 StringBuilder 的 append 方式的速度,要比直接对 String 使用“+”拼接的方式快的不是一点半点

那么,在实际开发中,对于需要多次或大量拼接的操作,在不考虑线程安全问题时,我们就应该尽可能使用 StringBuilder 进行 append 操作

除此之外,还有那些操作能够帮助我们提高字符串方面的运行效率呢?

StringBuilder 空参构造器的初始化大小为 16。那么,如果提前知道需要拼接 String 的个数,就应该直接使用带参构造器指定 capacity,以减少扩容的次数(扩容的逻辑可以自行查看源代码)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Constructs a string builder with no characters in it and an
* initial capacity of 16 characters.
*/
public StringBuilder() {
super(16);
}

/**
* Constructs a string builder with no characters in it and an
* initial capacity specified by the {@code capacity} argument.
*
* @param capacity the initial capacity.
* @throws NegativeArraySizeException if the {@code capacity}
* argument is less than {@code 0}.
*/
public StringBuilder(int capacity) {
super(capacity);
}

拼接操作总结:String可以和8种基本数据类型变量做运算,且运算只能是拼接运算,即只要一端有String类型,即为连接,运算的结果也为String。字符串参与运算时boolean类型的直接转换为字符串false/true,char类型的则是其字符展现形式。

1
2
3
4
5
6
7
8
9
10
11
12
13
String str = "Fly";
char c = 'a';
int i = 10;
boolean isOK = false;

//案例一:值为97+10+"Fly"=107Fly,此时+先为加运算,再为拼接
System.out.println(c + i + str);
//案例二:值为Flya10,此时+先做为拼接,做完拼接后结果类型为String,再做拼接
System.out.println(str + c + i);
//案例三:值为107Fly+false=107Flyfalse
System.out.println(c + i + str + isOK);
//案例四:编译失败(boolean类型不参与和基础类型的运算)
System.out.println(c + i + isOK + str);
1
2
3
4
5
6
7
8
//案例一:char类型在做运算的时候,是会转换为数值型的,值为:97+9+97=203
System.out.println('a' + '\t' + 'a');
//案例二:先基本类型char做数值运算,再和String做拼接运算,值为:106a
System.out.println('a' + '\t' + "a");
//案例三:先做拼接运算,然后后面均为拼接运算,值为:a a,其中中间的空格为转义字符\t
System.out.println("a" + '\t' + 'a');
//案例四:做拼接运算,值为:a a
System.out.println("a" + "\t" + "a");

3.5 通过new String的方式

格式:String str=new String("FlyShow");

生成的对象:栈空间str、str指向的堆对象、String堆对象里面存储在字符串常量池的value值对象(根据情况决定是否会在字符串常量池里面开辟)

原理分析:new String(String value)调用的构造器源码如下

1
2
3
4
5
6
7
8
9
10
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {

private final char value[]; //The value is used for character storage.
private int hash; //Default to 0

public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
}

编译后的代码以及内存图概览:

总结:几种创建字符串的方式

速记:Pool=>Police:literal、intern、constanadd ==>nb(new stringbuilder)

1
2
3
4
5
6
7
8
//字符串在常量池StringPool====》速记:Pool=>Police:literal、intern、constanadd
1、通过字面量literal赋值的方式String str="";
2、调用intern()方法
3、部分拼接(即常量拼接Constant Add):所有连接方均为常量

//字符串在堆里面:实际在String类里面的final byte[](jdk9及之后)或final char[](jdk8及之前)
1、通过new String()构造器传入
2、部分拼接:多个拼接方有一个非常量//其内部源码使用StringBuilder()。

一些截图案例

案例1

案例2

案例3

1
2
3
4
5
6
7
8
public static void test1() {
//都是常量,前端编译期会进行代码优化
//通过idea直接看对应的反编译的class文件,会显示 String s1 = "abc"; 说明做了代码优化
String s1 = "a" + "b" + "c";
String s2 = "abc";
// true,有上述可知,s1和s2实际上指向字符串常量池中的同一个值
System.out.println(s1 == s2);
}

案例4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void test5() {
String s1 = "javaEE";
String s2 = "hadoop";
String s3 = "javaEEhadoop";
String s4 = "javaEE" + "hadoop";
String s5 = s1 + "hadoop";
String s6 = "javaEE" + s2;
String s7 = s1 + s2;
System.out.println(s3 == s4); // true 编译期优化
System.out.println(s3 == s5); // false s1是变量,不能编译期优化
System.out.println(s3 == s6); // false s2是变量,不能编译期优化
System.out.println(s3 == s7); // false s1、s2都是变量
System.out.println(s5 == s6); // false s5、s6 不同的对象实例
System.out.println(s5 == s7); // false s5、s7 不同的对象实例
System.out.println(s6 == s7); // false s6、s7 不同的对象实例
String s8 = s6.intern();
System.out.println(s3 == s8); // true intern之后,s8和s3一样,指向字符串常量池中的"javaEEhadoop"
}

**
**举例6

1
2
3
4
5
6
7
public void test3(){
String s1 = "a";
String s2 = "b";
String s3 = "ab";
String s4 = s1 + s2;
System.out.println(s3==s4);
}

字节码:我们上面案例例的字节码进行查看,可以发现s1 + s2实际上是 new 了一个 StringBuilder 对象,并使用了 append 方法将 s1 和 s2 添加进来,最后调用了 toString 方法赋给 s4,而StringBuilder的toString方法就是new String()。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
0 ldc #2 <a>
2 astore_1
3 ldc #3 <b>
5 astore_2
6 ldc #4 <ab>
8 astore_3
9 new #5 <java/lang/StringBuilder>
12 dup
13 invokespecial #6 <java/lang/StringBuilder.<init>>
16 aload_1
17 invokevirtual #7 <java/lang/StringBuilder.append>
20 aload_2
21 invokevirtual #7 <java/lang/StringBuilder.append>
24 invokevirtual #8 <java/lang/StringBuilder.toString>
27 astore 4
29 getstatic #9 <java/lang/System.out>
32 aload_3
33 aload 4
35 if_acmpne 42 (+7)
38 iconst_1
39 goto 43 (+4)
42 iconst_0
43 invokevirtual #10 <java/io/PrintStream.println>
46 return

//而StringBuilder.toString()的源码
public final class StringBuilder extends AbstractStringBuilder implements java.io.Serializable, CharSequence{

char[] value;

@Override
public String toString() {
//Create a copy, don't share the array
return new String(value, 0, count);
}

public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= value.length) {
this.value = "".value;
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
}

5 StringTable 的垃圾回收

1
2
3
4
5
6
7
8
9
10
11
public class StringGCTest {
/**
* -Xms15m -Xmx15m -XX:+PrintGCDetails
*/
public static void main(String[] args) {

for (int i = 0; i < 100000; i++) {
String.valueOf(i).intern();
}
}
}

运行结果

1
2
3
4
5
6
7
8
9
10
11
12
[GC (Allocation Failure) [PSYoungGen: 4096K->504K(4608K)] 4096K->1689K(15872K), 0.0581583 secs] [Times: user=0.00 sys=0.00, real=0.06 secs] 
[GC (Allocation Failure) [PSYoungGen: 4600K->504K(4608K)] 5785K->2310K(15872K), 0.0015621 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
[GC (Allocation Failure) [PSYoungGen: 4600K->504K(4608K)] 6406K->2350K(15872K), 0.0034849 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
Heap
PSYoungGen total 4608K, used 1919K [0x00000000ffb00000, 0x0000000100000000, 0x0000000100000000)
eden space 4096K, 34% used [0x00000000ffb00000,0x00000000ffc61d30,0x00000000fff00000)
from space 512K, 98% used [0x00000000fff00000,0x00000000fff7e010,0x00000000fff80000)
to space 512K, 0% used [0x00000000fff80000,0x00000000fff80000,0x0000000100000000)
ParOldGen total 11264K, used 1846K [0x00000000ff000000, 0x00000000ffb00000, 0x00000000ffb00000)
object space 11264K, 16% used [0x00000000ff000000,0x00000000ff1cd9b0,0x00000000ffb00000)
Metaspace used 3378K, capacity 4496K, committed 4864K, reserved 1056768K
class space used 361K, capacity 388K, committed 512K, reserved 1048576K

6 G1 中的 String 去重操作

官网地址:JEP 192: String Deduplication in G1 (java.net)


Motivation

Many large-scale Java applications are currently bottlenecked on memory. Measurements have shown that roughly 25% of the Java heap live data set in these types of applications is consumed by String objects. Further, roughly half of those String objects are duplicates, where duplicates means string1.equals(string2) is true. Having duplicate String objects on the heap is, essentially, just a waste of memory. This project will implement automatic and continuous String deduplication in the G1 garbage collector to avoid wasting memory and reduce the memory footprint.


动机

目前,许多大规模的 Java 应用程序在内存上遇到了瓶颈。测量表明,在这些类型的应用程序中,大约 25%的 Java 堆实时数据集被String'对象所消耗。此外,这些 "String "对象中大约有一半是重复的,其中重复意味着 "string1.equals(string2) "是真的。在堆上有重复的String’对象,从本质上讲,只是一种内存的浪费。这个项目将在 G1 垃圾收集器中实现自动和持续的`String’重复数据删除,以避免浪费内存,减少内存占用。

注意这里说的重复,指的是在堆中的数据,而不是常量池中的,因为常量池中的本身就不会重复

背景:对许多 Java 应用(有大的也有小的)做的测试得出以下结果:

  • 堆存活数据集合里面 string 对象占了 25%
  • 堆存活数据集合里面重复的 string 对象有 13.5%
  • string 对象的平均长度是 45

许多大规模的 Java 应用的瓶颈在于内存,测试表明,在这些类型的应用里面,Java 堆中存活的数据集合差不多 25%是 String 对象。更进一步,这里面差不多一半 string 对象是重复的,重复的意思是说: stringl.equals(string2)= true。堆上存在重复的 String 对象必然是一种内存的浪费。这个项目将在 G1 垃圾收集器中实现自动持续对重复的 string 对象进行去重,这样就能避免浪费内存。


实现

  1. 当垃圾收集器工作的时候,会访问堆上存活的对象。对每一个访问的对象都会检查是否是候选的要去重的 String 对象
  2. 如果是,把这个对象的一个引用插入到队列中等待后续的处理。一个去重的线程在后台运行,处理这个队列。处理队列的一个元素意味着从队列删除这个元素,然后尝试去重它引用的 string 对象。
  3. 使用一个 hashtable 来记录所有的被 String 对象使用的不重复的 char 数组。当去重的时候,会查这个 hashtable,来看堆上是否已经存在一个一模一样的 char 数组。
  4. 如果存在,String 对象会被调整引用那个数组,释放对原来的数组的引用,最终会被垃圾收集器回收掉。
  5. 如果查找失败,char 数组会被插入到 hashtable,这样以后的时候就可以共享这个数组了。

命令行选项

1
2
3
4
5
6
# 开启String去重,默认是不开启的,需要手动开启。 
UseStringDeduplication(bool)
# 打印详细的去重统计信息
PrintStringDeduplicationStatistics(bool)
# 达到这个年龄的String对象被认为是去重的候选对象
StringpeDuplicationAgeThreshold(uintx)