Reprint: string constant Pool in Java detailed description

Source: Internet
Author: User

Referenced from: http://blog.csdn.net/langhong8/article/details/50938041

This article mainly introduces the string constant pool in Java in detail, the JVM in order to reduce the repetition of string object creation, it maintains a special memory, this memory is a string constant pool or string literal pool, the need for friends can refer to the next

There are two forms of string object creation in Java, one for literal form, such as String str = "Droid", and the other is to use the new standard method of constructing objects, such as String str = new String ("Droid"); Both of these methods are often used in code writing, especially in the literal way. However, there are some differences in performance and memory consumption between the two implementations. It all started with the JVM. In order to reduce the duplication of string objects, it maintains a special memory, which is a string constant pool or string literal pool.

Working principle

When a string object is created in the literal form of the code, the JVM first checks the literal, and if a reference to a string object of the same content exists in the string constant pool, the reference is returned, otherwise the new string object is created, then the reference is placed into the string constant pool, and the reference is returned.

Examples Show

Literal creation Form

Copy the Code code as follows:

String str1 = "Droid";

The JVM detects this literal, and here we think there is no content for the Droid object to exist. The JVM finds a string object with a string constant pool that does not exist, then creates the string object, then puts a reference to the object you just created into the string constant pool and returns the reference to the variable str1.

If there's a piece of code that follows

Copy the Code code as follows:

String str2 = "Droid";

The JVM also detects this literal, and the JVM finds the existence of the "Droid" string object by finding the string constant pool, and returns the reference to the variable str2 for the existing string object. Note that new string objects are not recreated here.

To verify that str1 and str2 point to the same object, we can pass this code

Copy the Code code as follows:

System.out.println (str1 = = str2);

The result is true.

Create with new

Copy the Code code as follows:

String str3 = new String ("Droid");

When we use new to construct a string object, a new string object is created, regardless of the reference to the object with the same content in the string constant pool. So let's test it with the code below,

Copy the Code code as follows:

String str3 = new String ("Droid");
System.out.println (str1 = = STR3);

The result, as we think, is false, which indicates that the two variables point to a different object.

Intern

For the string object created above using new, you can use the Intern method if you want to add a reference to this object to the string constant pool.

After calling intern, first check to see if there is a reference to the object in the string constant pool, and if so, return the reference to the variable, otherwise the reference is added and returned to the variable.

Copy the Code code as follows:

String STR4 = Str3.intern ();
System.out.println (STR4 = = str1);

The result of the output is true.

Difficult issues

Prerequisites?

The precondition of a string constant pool implementation is that the string object in Java is immutable, which ensures that multiple variables share the same object safely. If a string object in Java is mutable, and a reference operation alters the value of the object, then the other variables are affected, which is obviously unreasonable.

Referencing or objects

The problem is most common in strings that are stored in a constant pool as references or objects. A string constant pool holds an object reference, not an object. In Java, objects are created in heap memory.

Update verification, many comments received are also discussed in this issue, I have simply verified. Verify the Environment:

Copy the Code code as follows:

22:18:54-androidyue~/videos$ Cat/etc/os-release
Name=fedora
Version= "(Beefy Miracle)"
Id=fedora
Version_id=17
Pretty_name= "Fedora (beefy Miracle)"
Ansi_color= "0;34"
Cpe_name= "Cpe:/o:fedoraproject:fedora:17"

22:19:04-androidyue~/videos$ java-version
Java Version "1.7.0_25"
OpenJDK Runtime Environment (FEDORA-2.3.12.1.FC17-X86_64)
OpenJDK 64-bit Server VM (build 23.7-b01, Mixed mode)

Verify the idea: The following Java program reads a 82M size video file, intern operation as a string.

Copy the Code code as follows:

22:01:17-androidyue~/videos$ LL-LH | grep why_to_learn.mp4
-rw-rw-r--. 1 Androidyue androidyue 82M Oct why_to_learn.mp4

Validation code

Copy the Code code as follows:

Import Java.io.BufferedReader;
Import java.io.FileNotFoundException;
Import Java.io.FileReader;
Import java.io.IOException;

public class Testmain {
private static String filecontent;
public static void Main (string[] args) {
Filecontent = readfiletostring (Args[0]);
if (null! = filecontent) {
Filecontent = Filecontent.intern ();
System.out.println ("not Null");
}
}
private static string readfiletostring (string file) {
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader (file));
StringBuffer buff = new StringBuffer ();
String Line;
while (line = Reader.readline ()) = null) {
Buff.append (line);
}
return buff.tostring ();
} catch (FileNotFoundException e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
} finally {
if (null! = Reader) {
try {
Reader.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}
return null;
}
}

Because the string constant pool exists in heap memory for a permanent generation, it applies to Java8. We validate by setting a very small value for the permanent generation. If a string object exists in a string constant pool, then the Java.lang.OutOfMemoryError PermGen space error must be thrown.

Copy the Code code as follows:

java-xx:permsize=6m Testmain ~/videos/why_to_learn.mp4

Running the certification program does not throw oom, in fact, this is not a good proof that the storage is an object or reference.

But the actual content object char[, which at least proves the string, is not stored in the string constant pool. In this case, it is not so important that the string constant pool stores a string object or a reference to a string object. But the individual is still inclined to store the reference.

Advantages and Disadvantages

The advantage of a string constant pool is to reduce the creation of the same content string, saving memory space.

If hard to say the disadvantage, it is to sacrifice the CPU computing time to change space. CPU compute time is primarily used to look up a reference in a string constant pool for the content of the same object. However, its internal implementation is Hashtable, so the computational cost is lower.

GC Recycling?

Because a string constant pool holds a reference to a shared string object, does that mean that these objects cannot be recycled?

The objects that are shared in the first question are generally small. As far as I am aware, this problem does exist in earlier versions, but with the introduction of weak references, the problem should not be present.

On this issue, you can learn more about this article interned Strings:java Glossary

Intern use?

The premise of using intern is that you know you really need to use it. For example, we have a record of millions of records, one of which has been recorded several times in the state of California, and we do not want to create a string object like millions, and we can use intern to keep only one copy in memory. For more in-depth understanding of intern, please refer to the in-depth parsing string#intern.

There's always an exception?

Do you know the following code that creates several string objects and saves a few references in a string constant pool?

Copy the Code code as follows:

String test = "a" + "B" + "C";

The answer is that only one object is created and only one reference is saved in the constant pool. We can see it by using JAVAP anti-compilation.

Copy the Code code as follows:

17:02 $ javap-c TESTINTERNEDPOOLGC
Compiled from "Testinternedpoolgc.java"
public class TESTINTERNEDPOOLGC extends java.lang.object{
public TESTINTERNEDPOOLGC ();
Code:
0:aload_0
1:invokespecial #1; Method java/lang/object. " <init> ":() V
4:return

public static void Main (java.lang.string[]) throws java.lang.Exception;
Code:
0:LDC #2; String ABC
2:astore_1
3:return

See, actually, during compilation, these three literals have been synthesized in one. This is actually an optimization, avoiding the creation of redundant string objects, and the problem of string stitching does not occur. For string stitching, you can view Java details: concatenation of strings.

Reprint: string constant Pool in Java detailed description

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.