字符串常量池String Table
String的基本特性
String 概述
String 的概述
-
String:字符串,使用一对""引起来表示。
String s1 = "hello"; // 字面量的定义方式 String s2 = new String("hello"); // new 对象的方式
-
String声明为final的,不可被继承
-
String实现了Serializable接口:表示字符串是支持序列化的。 实现了Comparable接口:表示String可以比较大小
-
String在jdk8及以前内部定义了final char[],value用于存储字符串数据。jdk9时改为byte[]
JDK 1.8
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
Java 15
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/**
* The value is used for character storage.
*
* @implNote This field is trusted by the VM, and is a subject to
* constant folding if String instance is constant. Overwriting this
* field after construction will cause problems.
*
* Additionally, it is marked with {@link Stable} to trust the contents
* of the array. No other facility in JDK provides this functionality (yet).
* {@link Stable} is safe here, because value is never null.
*/
@Stable
private final byte[] value;
String 在jdk9中存储结构变更
- String类的当前实现将字符存储在char数组中,每个字符使用两个字节(16位)。
- 从许多不同的应用程序收集的数据表明,字符串是堆使用的主要组成部分,而且大多数字符串对象只包含拉丁字符。这些字符只需要一个字节的存储空间,因此这些字符串对象的内部char数组中有一半的空间将不会使用。
- 之前 String 类使用 UTF-16 的 char[] 数组存储,现在改为 byte[] 数组 外加一个编码标志位存储,该编码标志将指定 String 类中 byte[] 数组的编码方式
结论:String再也不用char[]
来存储了,改成了byte []
加上编码标记,节约了一些空间
同时基于String的数据结构,例如StringBuffer
和StringBuilder
也同样做了修改
String 的基本特征
String:代表不可变的字符序列。简称:不可变性。
- 当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值。
- 当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。
- 当调用String的replace()方法修改指定字符或字符串时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。
通过字面量的方式(区别于new)给一个字符串赋值,此时的字符串值声明在字符串常量池中。
代码示例
import org.junit.jupiter.api.Test;
/**
* String的基本使用:体现String的不可变性
*/
public class StringTest1 {
@Test
public void test1() {
String s1 = "abc";
// 字面量定义的方式,"abc"存储在字符串常量池中
String s2 = "abc";
// s1 = "hello";
// 判断地址:true --> false
System.out.println(s1 == s2);
// abc
System.out.println(s1);
// abc
System.out.println(s2);
}
@Test
public void test2() {
String s1 = "abc";
String s2 = "abc";
s2 += "def";
// abcdef
System.out.println(s2);
// abc
System.out.println(s1);
}
@Test
public void test3() {
String s1 = "abc";
String s2 = s1.replace('a', 'm');
//abc
System.out.println(s1);
//mbc
System.out.println(s2);
}
}
String 的基本特征2
字符串常量池中是不会存储相同内容的字符串的。
- String的String Pool 是一个固定大小的Hashtable,默认值大小长度是1009。如果放进StringPool的String非常多, 就会造成Hash冲突严重,从而导致链表会很长,而链表长了后直接会造成的影响就是当调用String. intern时性能会大幅下降。
- 使用
-XX: StringTableSize
可设置StringTable的长度。 - 在jdk6中StringTable是固定的,就是1009的长度,所以如果常量池中的字符串过多就会导致效率下降很快。StringTableSize设 置没有要求。
- 在jdk7中,StringTable的长度默认值是60013。
- jdk8开始,1009是StringTable长度可设置的最小值。
代码示例:设置 StringTable 的长度
/**
* -XX:StringTableSize=1009
*/
public class StringTest2 {
public static void main(String[] args) {
// 测试StringTableSize参数
System.out.println("我来打个酱油");
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
JDK 1.6
JDK 1.7
手动设置前
手动设置后
JDK 1.8
如果小于1009则会报错
代码示例2:测试不同StringTable长度下,程序的性能
产生10万个长度不超过10的字符串
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
/**
* 产生10万个长度不超过10的字符串
*/
public class GenerateString {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("words.txt");
for (int i = 0; i < 100000; i++) {
int length = (int) (Math.random() * (10 - 1 + 1) + 1);
fw.write(getString(length) + "\n");
}
fw.close();
}
private static String getString(int length) {
String str = "";
Random random = new Random();
for (int i = 0; i < length; i++) {
boolean bool = random.nextBoolean();
if (bool) {
int num = (int) (Math.random() * 27 + 65);
str += (char) num;
} else {
int num = (int) (Math.random() * 27 + 97);
str += (char) num;
}
}
return str;
}
}
测试方法
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* -XX:StringTableSize=1009
*/
public class StringTest2 {
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("words.txt"));
long start = System.currentTimeMillis();
String data;
while ((data = br.readLine()) != null) {
// 如果字符串常量池中没有对应data的字符串的话,则在常量池中生成
data.intern();
}
long end = System.currentTimeMillis();
System.out.println("花费的时间为:" + (end - start));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
结果
1009
100009
String的内存分配
在Java语言中有8种基本数据类型和一种比较特殊的类型String。这些 类型为了使它们在运行过程中速度更快、更节省内存,都提供了一种常量池的概念。
常量池就类似一个Java系统级别提供的缓存。8种基本数据类型的常量 池都是系统协调的,String类型的常量池比较特殊。它的主要使用方法有两种。
- 直接使用双引号声明出来的String对象会直接存储在常量池中。
- 比如:
String info = "abc";
- 比如:
- 如果不是用双引号声明的String对象,可以使用String提供的intern()方法。这个后面重点谈
Java 6及以前,字符串常量池存放在永久代。
Java 7中Oracle的工程师对字符串池的逻辑做了很大的改变,即将字符串常量池的位置调整到Java堆内。
- 所有的字符串都保存在堆(Heap)中,和其他普通对象一样,这样可以让你在进行调优应用时仅需要调整堆大小就可以了。
- 字符串常量池概念原本使用得比较多,但是这个改动使得我们有足够的理由让我们重新考虑在Java 7中使用String. intern()。
Java8元空间,字符串常量在堆
为什么要调整 String 位置
https://www.oracle.com/java/technologies/javase/jdk7-relnotes.html#jdk7changes
-
为什么要调整位置?
- 永久代的默认比较小
- 永久代垃圾回收频率低
- 堆中空间足够大,字符串可被及时回收
-
在JDK 7中,interned字符串不再在Java堆的永久代中分配,而是在Java堆的主要部分(称为年轻代和年老代)中分配,与应用程序创建的其他对象一起分配。
-
此更改将导致驻留在主Java堆中的数据更多,驻留在永久生成中的数据更少,因此可能需要调整堆大小。
代码示例
import java.util.HashSet;
import java.util.Set;
/**
* jdk6中:
* -XX:PermSize=6m -XX:MaxPermSize=6m -Xms6m -Xmx6m
* <p>
* jdk8中:
* -XX:MetaspaceSize=6m -XX:MaxMetaspaceSize=6m -Xms6m -Xmx6m
*/
public class StringTest3 {
public static void main(String[] args) {
// 使用Set保持着常量池引用,避免full gc回收常量池行为
Set<String> set = new HashSet<>();
// 在short可以取值的范围内足以让6MB的PermSize或heap产生OOM了。
short i = 0;
while (true) {
set.add(String.valueOf(i++).intern());
}
}
}
JDK 1.6
JDK 1.8
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.HashMap.resize(HashMap.java:703)
at java.util.HashMap.putVal(HashMap.java:662)
at java.util.HashMap.put(HashMap.java:611)
at java.util.HashSet.add(HashSet.java:219)
at com.atguigu.java.StringTest3.main(StringTest3.java:22)
Process finished with exit code 1
String 的基本操作
Java语言规范里要求完全相同的字符串字面量,应该包含同样的Unicode字符序列(包含同一份码点序列的常量),并且必须是指向同一个String类实例。
代码示例1
public class StringTest4 {
public static void main(String[] args) {
System.out.println();//2198
System.out.println("1");//2199
System.out.println("2");//2200
System.out.println("3");
System.out.println("4");
System.out.println("5");
System.out.println("6");
System.out.println("7");
System.out.println("8");
System.out.println("9");
System.out.println("10");//2208
//如下的字符串"1" 到 "10"不会再次加载
System.out.println("1");//2209
System.out.println("2");//2209
System.out.println("3");
System.out.println("4");
System.out.println("5");
System.out.println("6");
System.out.println("7");
System.out.println("8");
System.out.println("9");
System.out.println("10");//2341
}
}
加载完1之后为2200
第一次加载到10,为2209
下一次加载依旧1依旧是2209
代码示例2
public class Memory {
public static void main(String[] args) {//line 1
int i = 1;//line 2
Object obj = new Object();//line 3
Memory mem = new Memory();//line 4
mem.foo(obj);//line 5
}//line 9
private void foo(Object param) {//line 6
String str = param.toString();//line 7
System.out.println(str);
}//line 8
}
https://www.journaldev.com/4098/java-heap-space-vs-stack-memory
Let’s go through the steps of the execution of the program.
- As soon as we run the program, it loads all the Runtime classes into the Heap space. When the main() method is found at line 1, Java Runtime creates stack memory to be used by main() method thread.
- We are creating primitive local variable at line 2, so it’s created and stored in the stack memory of main() method.
- Since we are creating an Object in the 3rd line, it’s created in heap memory and stack memory contains the reference for it. A similar process occurs when we create Memory object in the 4th line.
- Now when we call the foo() method in the 5th line, a block in the top of the stack is created to be used by the foo() method. Since Java is pass-by-value, a new reference to Object is created in the foo() stack block in the 6th line.
- A string is created in the 7th line, it goes in the String Pool in the heap space and a reference is created in the foo() stack space for it.
- foo() method is terminated in the 8th line, at this time memory block allocated for foo() in stack becomes free.
- In line 9, main() method terminates and the stack memory created for main() method is destroyed. Also, the program ends at this line, hence Java Runtime frees all the memory and ends the execution of the program.
字符串拼接操作
常量与常量的拼接结果在常量池,原理是编译期优化。
常量池中不会存在相同内容的变量。
只要其中有一个是变量,结果就在堆中。变量拼接的原理是StringBuilder。
如果拼接的结果调用intern()方法,则主动将常量池中还没有的字符串对象放入池中,并返回此对象地址
- 如果存在,则返回字符串在常量池中的地址。
- 如果字符串常量池中不存在该字符串,则在常量池中创建一份,并返回此对象的地址。
常量与常量的拼接结果在常量池,原理是编译期优化
@Test
public void test1() {
String s1 = "a" + "b" + "c";// 编译期优化:等同于"abc"
String s2 = "abc"; // "abc"一定是放在字符串常量池中,将此地址赋给s2
/*
最终.java编译成.class,再执行.class
String s1 = "abc";
String s2 = "abc"
*/
System.out.println(s1 == s2); // true
System.out.println(s1.equals(s2)); // true
}
在IDEA中查看反编译后的结果可以看到s1已经变成了"abc"
从字节码指令看出:编译器做了优化,将 “a” + “b” + “c” 优化成了 “abc”
拼接前后,只要其中有一个是变量,结果就在堆中
@Test
public void test2() {
String s1 = "javaEE";
String s2 = "hadoop";
String s3 = "javaEEhadoop";
String s4 = "javaEE" + "hadoop";// 编译期优化
// 如果拼接符号的前后出现了变量,则相当于在堆空间中new String(),具体的内容为拼接的结果:javaEEhadoop
String s5 = s1 + "hadoop";
String s6 = "javaEE" + s2;
String s7 = s1 + s2;
System.out.println(s3 == s4);//true
System.out.println(s3 == s5);//false
System.out.println(s3 == s6);//false
System.out.println(s3 == s7);//false
System.out.println(s5 == s6);//false
System.out.println(s5 == s7);//false
System.out.println(s6 == s7);//false
// intern():判断字符串常量池中是否存在javaEEhadoop值,如果存在,则返回常量池中javaEEhadoop的地址;
// 如果字符串常量池中不存在javaEEhadoop,则在常量池中加载一份javaEEhadoop,并返回次对象的地址。
String s8 = s6.intern();
System.out.println(s3 == s8);//true
}
字符串拼接的底层细节
代码示例1
@Test
public void test3(){
String s1 = "a";
String s2 = "b";
String s3 = "ab";
/*
如下的s1 + s2 的执行细节:(变量s是我临时定义的)
① StringBuilder s = new StringBuilder();
② s.append("a")
③ s.append("b")
④ s.toString() --> 约等于 new String("ab")
补充:在jdk5.0之后使用的是StringBuilder,在jdk5.0之前使用的是StringBuffer
*/
String s4 = s1 + s2;// "ab"
System.out.println(s3 == s4);// false
}
@Override
public String toString() {
// Create a copy, don't share the array
return new String(value, 0, count);
}
字节码指令
0 ldc #14 <a>
2 astore_1
3 ldc #15 <b>
5 astore_2
6 ldc #16 <ab>
8 astore_3
9 new #9 <java/lang/StringBuilder>
12 dup
13 invokespecial #10 <java/lang/StringBuilder.<init>>
16 aload_1
17 invokevirtual #11 <java/lang/StringBuilder.append>
20 aload_2
21 invokevirtual #11 <java/lang/StringBuilder.append>
24 invokevirtual #12 <java/lang/StringBuilder.toString>
27 astore 4
29 getstatic #3 <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 #4 <java/io/PrintStream.println>
46 return
分析拼接的步骤
- new StringBuilder()
9 new #9 <java/lang/StringBuilder>
12 dup
13 invokespecial #10 <java/lang/StringBuilder.<init>>
- 加载字符串变量,进行 append 操作
16 aload_1
17 invokevirtual #11 <java/lang/StringBuilder.append>
20 aload_2
21 invokevirtual #11 <java/lang/StringBuilder.append>
- 调用 StringBuilder 类的 toString() 方法,转换为字符串,并存储在局部变量中
24 invokevirtual #12 <java/lang/StringBuilder.toString>
27 astore 4
代码示例2
/**
* 1. 字符串拼接操作不一定使用的是StringBuilder!
* 如果拼接符号左右两边都是字符串常量或常量引用,则仍然使用编译期优化,即非StringBuilder的方式。
* 2. 针对于final修饰类、方法、基本数据类型、引用数据类型的量的结构时,能使用上final的时候建议使用上。
*/
@Test
public void test4() {
final String s1 = "a";
final String s2 = "b";
String s3 = "ab";
String s4 = s1 + s2;
System.out.println(s3 == s4);//true
}
IDEA反编译结果
代码示例3
@Test
public void test5() {
String s1 = "javaEEhadoop";
String s2 = "javaEE";
String s3 = s2 + "hadoop";
System.out.println(s1 == s3);//false
final String s4 = "javaEE";//s4:常量
String s5 = s4 + "hadoop";
System.out.println(s1 == s5);//true
}
拼接操作与 append 操作的效率对比
@Test
public void test6() {
long start = System.currentTimeMillis();
method1(100000);// 5368
// method2(100000);// 5
long end = System.currentTimeMillis();
System.out.println("花费的时间为:" + (end - start));
}
public void method1(int highLevel) {
String src = "";
for (int i = 0; i < highLevel; i++) {
src = src + "a";// 每次循环都会创建一个StringBuilder、String
}
}
public void method2(int highLevel) {
// 只需要创建一个StringBuilder
StringBuilder src = new StringBuilder();
for (int i = 0; i < highLevel; i++) {
src.append("a");
}
}
体会执行效率:通过StringBuilder的append()的方式添加字符串的效率要远高于使用String的字符串拼接方式!
分析原因:
- StringBuilder的append()的方式:自始至终中只创建过一个StringBuilder的对象;使用String的字符串拼接方式:创建过多个StringBuilder和String的对象
- 使用String的字符串拼接方式:内存中由于创建了较多的StringBuilder和String的对象,内存占用更大;如果进行GC,需要花费额外的时间。
改进的空间:
- 在实际开发中,如果基本确定要前前后后添加的字符串长度不高于某个限定值highLevel的情况下,建议使用构造器实例化:
StringBuilder s = new StringBuilder(highLevel); //new char[highLevel]
关于 StringBuilder 构造器
StringBuilder 构造器:可传入一个 int 类型的变量,用于初始化内部的 char[] 数组
/**
* 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);
}
AbstractStringBuilder(StringBuilder 的父类)的构造器
/**
* Creates an AbstractStringBuilder of the specified capacity.
*/
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
intern() 的使用
intern() 方法的说明
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#intern--
intern是一个native方法,调用的是底层C的方法
字符串池最初是空的,由String类私有地维护。在调用intern方法时,如果池中已经包含了由equals(object)方法确定的与该字符串对象相等的字符串,则返回池中的字符串。否则,该字符串对象将被添加到池中,并返回对该字符串对象的引用。
如果不是用双引号声明的String对象,可以使用String提供的intern方法:intern方法会从字符串常量池中查询当前字符串是否存在,若不存在就会将当前字符串放入常量池中。比如:
String myInfo = new string("I love atguigu").intern();
也就是说,如果在任意字符串上调用String.intern方法,那么其返回结果所指向的那个类实例,必须和直接以常量形式出现的字符串实例完全相同。因此,下列表达式的值必定是true
("a"+"b"+"c").intern()=="abc"
通俗点讲,Interned String就是确保字符串在内存里只有一份拷贝,这样可以节约内存空间,加快字符串操作任务的执行速度。注意,这个值会被存放在字符串内部池(String Intern Pool)
代码示例
/**
* 如何保证变量s指向的是字符串常量池中的数据呢?
* 有两种方式:
* 方式一: String s = "shkstart";// 字面量定义的方式
* 方式二: 调用intern()
* String s = new String("shkstart").intern();
* String s = new StringBuilder("shkstart").toString().intern();
*/
public class StringIntern {
public static void main(String[] args) {
String s = new String("1");
String s1 = s.intern();// 调用此方法之前,字符串常量池中已经存在了"1"
String s2 = "1";
// s 指向堆空间"1"的内存地址
// s1 指向字符串常量池中"1"的内存地址
// s2 指向字符串常量池已存在的"1"的内存地址 所以 s1==s2
System.out.println(s == s2);// jdk6:false jdk7/8:false
System.out.println(s1 == s2);// jdk6: true jdk7/8:true
System.out.println(System.identityHashCode(s));// 491044090
System.out.println(System.identityHashCode(s1));// 644117698
System.out.println(System.identityHashCode(s2));// 644117698
// s3变量记录的地址为:new String("11")
String s3 = new String("1") + new String("1");
// 执行完上一行代码以后,字符串常量池中,是否存在"11"呢?答案:不存在!!
// 在字符串常量池中生成"11"。如何理解:jdk6:创建了一个新的对象"11",也就有新的地址。
// jdk7:此时常量中并没有创建"11",而是创建一个指向堆空间中new String("11")的地址
s3.intern();
// s4变量记录的地址:使用的是上一行代码代码执行时,在常量池中生成的"11"的地址
String s4 = "11";
System.out.println(s3 == s4);// jdk6:false jdk7/8:true
}
}
new String() 的说明
题目:new String("ab")会创建几个对象?
代码
/**
* 题目:
* new String("ab")会创建几个对象?看字节码,就知道是两个。
* 一个对象是:new关键字在堆空间创建的
* 另一个对象是:字符串常量池中的对象"ab"。 字节码指令:ldc
*/
public class StringNewTest {
public static void main(String[] args) {
String str = new String("ab");
}
}
字节码
0 new #2 <java/lang/String>
:在堆中创建了一个 String 对象4 ldc #3 <ab>
:在字符串常量池中放入 “ab”(如果之前字符串常量池中没有 “ab” 的话)
拓展:new String("a") + new String("b")
代码示例
/**
* 思考:
* new String("a") + new String("b")呢?
* 对象1:new StringBuilder()
* 对象2:new String("a")
* 对象3:常量池中的"a"
* 对象4:new String("b")
* 对象5:常量池中的"b"
* <p>
* 深入剖析: StringBuilder的toString():
* 对象6 :new String("ab")
* 强调一下,toString()的调用,在字符串常量池中,没有生成"ab"
*/
public class StringNewTest {
public static void main(String[] args) {
String str = new String("a") + new String("b");
}
}
字节码
0 new #2 <java/lang/StringBuilder>
:拼接字符串会创建一个 StringBuilder 对象7 new #4 <java/lang/String>
:创建 String 对象,对应于 new String(“a”)11 ldc #5 <a>
:在字符串常量池中放入 “a”(如果之前字符串常量池中没有 “a” 的话)19 new #4 <java/lang/String>
:创建 String 对象,对应于 new String(“b”)23 ldc #8 <b>
:在字符串常量池中放入 “b”(如果之前字符串常量池中没有 “b” 的话)31 invokevirtual #9 <java/lang/StringBuilder.toString>
:调用 StringBuilder 的 toString() 方法,会生成一个 String 对象
代码示例
/**
* 如何保证变量s指向的是字符串常量池中的数据呢?有两种方式:
* 方式一: String s = "shkstart";//字面量定义的方式
* 方式二: 调用intern()
* String s = new String("shkstart").intern();
* String s = new StringBuilder("shkstart").toString().intern();
*/
public class StringIntern1 {
public static void main(String[] args) {
String s = new String("1");
s.intern();// 这方法其实没啥屌用,调用此方法之前,字符串常量池中已经存在"1"
String s2 = "1";
/*
jdk6:false jdk7/8:false
因为 s 指向堆空间中的 "1" ,s2 指向字符串常量池中的 "1"
*/
System.out.println(s == s2);
// 执行完下一行代码以后,字符串常量池中,是否存在"11"呢?答案:不存在!!
String s3 = new String("1") + new String("1");// s3变量记录的地址为:new String("11")
/*
如何理解:jdk6:创建了一个新的对象"11",也就有新的地址。
jdk7:此时常量中并没有创建"11",而是在常量池中记录了指向堆空间中new String("11")的地址(节省空间)
*/
s3.intern(); // 在字符串常量池中生成"11"。
String s4 = "11";// s4变量记录的地址:使用的是上一行代码代码执行时,在常量池中生成的"11"的地址
// jdk6:false jdk7/8:true
System.out.println(s3 == s4);
}
}
JDK 1.6
JDK 1.7/1.8
拓展
/**
* 如何保证变量s指向的是字符串常量池中的数据呢?有两种方式:
* 方式一: String s = "shkstart";//字面量定义的方式
* 方式二: 调用intern()
* String s = new String("shkstart").intern();
* String s = new StringBuilder("shkstart").toString().intern();
*/
public class StringIntern1 {
public static void main(String[] args) {
// 执行完下一行代码以后,字符串常量池中,是否存在"11"呢?答案:不存在!!
String s3 = new String("1") + new String("1");// new String("11")
// 在字符串常量池中生成对象"11"
String s4 = "11";
String s5 = s3.intern();
// s3 是堆中的 "ab" ,s4 是字符串常量池中的 "ab"
System.out.println(s3 == s4);// false
// s5 是从字符串常量池中取回来的引用,当然和 s4 相等
System.out.println(s5 == s4);// true
}
}
总结String的intern()的使用
jdk1.6中,将这个字符串对象尝试放入串池。
- 如果字符串常量池中有,则并不会放入。返回已有的串池中的对象的地址
- 如果没有,会把此对象复制一份,放入串池,并返回串池中的对象地址
Jdk1.7起,将这个字符串对象尝试放入串池。
- 如果字符串常量池中有,则并不会放入。返回已有的串池中的对象的地址
- 如果没有,则会把对象的引用地址复制一份,放入串池,并返回串池中的引用地址
intern() 方法的练习
练习1
public class StringExer1 {
public static void main(String[] args) {
// String x = "ab";
String s = new String("a") + new String("b");// new String("ab")
// 在上一行代码执行完以后,字符串常量池中并没有"ab"
String s2 = s.intern();// jdk6中:在串池中创建一个字符串"ab"
// jdk8中:串池中没有创建字符串"ab",而是创建一个引用,指向new String("ab"),将此引用返回
System.out.println(s2 == "ab");// jdk6:true jdk8:true
System.out.println(s == "ab");// jdk6:false jdk8:true
}
}
JDK1.6
在串池中创建一个字符串"ab"
JDK 1.7/1.8 中:
串池中没有创建字符串"ab",而是创建一个引用,指向new String(“ab”),将此引用返回
练习2
public class StringExer1 {
public static void main(String[] args) {
// 在这儿加一句
String x = "ab";
//在下一行代码执行完以后,字符串常量池中并没有"ab"
String s = new String("a") + new String("b");//new String("ab")
/*
jdk6中:在串池中创建一个字符串"ab"
jdk8中:串池中没有创建字符串"ab",而是创建一个引用,指向new String("ab"),将此引用返回
*/
String s2 = s.intern();
System.out.println(s2 == "ab");//jdk6:true jdk8:true
System.out.println(s == "ab");//jdk6:false jdk8:false
}
}
练习3
public class StringExer2 {
public static void main(String[] args) {
String s1 = new String("ab");// 执行完以后,会在字符串常量池中会生成"ab"
s1.intern();
String s2 = "ab";
System.out.println(s1 == s2); // false
}
}
练习4
public class StringExer2 {
/**
* 对象内存地址可以使用System.identityHashCode(object)方法获取
*
* @param args
*/
public static void main(String[] args) {
String s1 = new String("a") + new String("b");//执行完以后,不会在字符串常量池中会生成"ab"
System.out.println(System.identityHashCode(s1));// 1132721997
s1.intern();
System.out.println(System.identityHashCode(s1));// 1132721997
String s2 = "ab";
System.out.println(System.identityHashCode(s2));// 142786591
System.out.println(s1 == s2); // false
}
}
intern() 方法效率测试
/**
* 使用intern()测试执行效率:空间使用上
* 结论:对于程序中大量存在存在的字符串,尤其其中存在很多重复字符串时,使用intern()可以节省内存空间。
*/
public class StringIntern2 {
static final int MAX_COUNT = 1000 * 10000;
static final String[] arr = new String[MAX_COUNT];
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])); // 3558
// arr[i] = new String(String.valueOf(data[i % data.length])).intern(); // 2982
}
long end = System.currentTimeMillis();
System.out.println("花费的时间为:" + (end - start));
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.gc();
}
}
不适用intern()
使用intern()
结论
对于程序中大量使用存在的字符串时,尤其存在很多已经重复的字符串时,使用intern()方法能够节省内存空间。
大的网站平台,需要内存中存储大量的字符串。比如社交网站,很多人都存储:北京市、海淀区等信息。这时候如果字符串都调用intern() 方法,就会很明显降低内存的大小。
StringTable 的垃圾回收
代码
/**
* String的垃圾回收:
* -Xms15m -Xmx15m -XX:+PrintStringTableStatistics -XX:+PrintGCDetails
*/
public class StringGCTest {
public static void main(String[] args) {
for (int j = 0; j < 100000; j++) {
String.valueOf(j).intern();
}
}
}
程序日志:
- 在 PSYoungGen 区发生了垃圾回收
- Number of entries 和 Number of literals 明显没有 100000
- 以上两点均说明 StringTable 区发生了垃圾回收
[GC (
Allocation Failure) [PSYoungGen: 4096K->512K(4608K)] 4096K->680K(15872K), 0.0070234 secs] [Times: user=0.00 sys=0.00, real=0.01 secs]
Heap
PSYoungGen total 4608K, used 3628K [0x00000000ffb00000, 0x0000000100000000, 0x0000000100000000)
eden space 4096K, 76% used [0x00000000ffb00000,0x00000000ffe0b000,0x00000000fff00000)
from space 512K, 100% used [0x00000000fff00000,0x00000000fff80000,0x00000000fff80000)
to space 512K, 0% used [0x00000000fff80000,0x00000000fff80000,0x0000000100000000)
ParOldGen total 11264K, used 168K [0x00000000ff000000, 0x00000000ffb00000, 0x00000000ffb00000)
object space 11264K, 1% used [0x00000000ff000000,0x00000000ff02a010,0x00000000ffb00000)
Metaspace used 3221K, capacity 4496K, committed 4864K, reserved 1056768K
class space used 350K, capacity 388K, committed 512K, reserved 1048576K
SymbolTable statistics:
Number of buckets : 20011 = 160088 bytes, avg 8.000
Number of entries : 13236 = 317664 bytes, avg 24.000
Number of literals : 13236 = 566352 bytes, avg 42.789
Total footprint : = 1044104 bytes
Average bucket size : 0.661
Variance of bucket size : 0.662
Std. dev. of bucket size: 0.814
Maximum bucket size : 6
StringTable statistics:
Number of buckets : 60013 = 480104 bytes, avg 8.000
Number of entries : 57818 = 1387632 bytes, avg 24.000
Number of literals : 57818 = 3297152 bytes, avg 57.026
Total footprint : = 5164888 bytes
Average bucket size : 0.963
Variance of bucket size : 0.760
Std. dev. of bucket size: 0.872
Maximum bucket size : 5
Process finished with exit code 0
G1 中的 String 去重操作
String 去重操作的背景
背景:对许多Java应用(有大的也有小的)做的测试得出以下结果:
- 堆存活数据集合里面String对象占了25%
- 堆存活数据集合里面重复的String对象有13.5%
- String对象的平均长度是45
许多大规模的Java应用的瓶颈在于内存,测试表明,在这些类型的应用里面,Java堆中存活的数据集合差不多25%是String对象。
更进一步,这里面差不多一半String对象是重复的,重复的意思是说:str1.equals(str2) == true。堆上存在重复的String对象必然是一种内存的浪费。这个项目将在G1垃圾收集器中实现自动持续对重复的String对象进行去重,这样就能避免浪费内存。
String 去重的的具体实现
- 当垃圾收集器工作的时候,会访问堆上存活的对象。对每一个访问的对象都会检查是否是候选的要去重的String对象。
- 如果是,把这个对象的一个引用插入到队列中等待后续的处理。一个去重的线程在后台运行,处理这个队列。处理队列的一个元素意味着从队列删除这个元素,然后尝试去重它引用的String对象。
- 使用一个Hashtable来记录所有的被String对象使用的不重复的char数组。当去重的时候,会查这个Hashtable,来看堆上是否已经存在一个一模一样的char数组。
- 如果存在,String对象会被调整引用那个数组,释放对原来的数组的引用,最终会被垃圾收集器回收掉。
- 如果查找失败,char数组会被插入到Hashtable,这样以后的时候就可以共享这个数组了。
命令行选项
- UseStringDeduplication(bool) :开启String去重,默认是不开启的,需要手动开启。
- PrintStringDeduplicationStatistics(bool) :打印详细的去重统计信息
- StringDeduplicationAgeThreshold(uintx) :达到这个年龄的String对象被认为是去重的候选对象