A pool of string constants in Java
There are two forms of string object creation in Java, one in literal form, such as string str = "Droid", and the other is the method of using the standard constructed object of new, such as string str = new String ("Droid "), both of which we often use in code writing, especially in literal ways. However, there are some differences in performance and memory usage between these two implementations. It all stems from the JVM in order to reduce the duplication of string objects, it maintains a special memory, which is either a string constant pool or a string literal pool.
Working principle
When you create a string object in literal form in code, the JVM first checks this literal and returns the reference if there is a reference to the string object of the same content in the string constant pool, otherwise the new string object is created, and then the reference is placed in a string constant pool and returned.
Give an example to explain
Literal creation Form
String str1 = "Droid";
The JVM detects this literal, and here we think there is no content for the Droid object to exist. The JVM cannot find a string object with a string constant pool that is not in existence, then creates the string object, then puts the reference of the object just created into the string constant pool and returns the reference to the variable str1.
If there's a piece of code next
String str2 = "Droid";
Similarly, the JVM still detects this literal, and the JVM finds that the contents are "Droid" string objects by looking for a constant pool of strings, and then returns a reference to the existing string object to the variable str2. Note that the new string object is not recreated here.
To verify whether STR1 and str2 point to the same object, we can pass this code
System.out.println (str1 = = str2);
The result is true.
Using new to create
String str3 = new String ("Droid");
When we use new to construct a string object, a new string object is created regardless of whether there is a reference to the object in the string constant pool that has the same content. So we use the following code to test
String str3 = new String ("Droid");
System.out.println (str1 = = STR3);
The result, as we think, is false, indicating that the two variables point to a different object.
Intern
For a string object created above using new, you can use the Intern method if you want to add a reference to the object to a string constant pool.
After calling intern, first check that the string constant pool has a reference to the object, and if so, return the reference to the variable, otherwise the reference is added and returned to the variable.
String STR4 = Str3.intern ();
System.out.println (STR4 = = str1);
The result of the output is true.
Difficult issues
Prerequisites?
The prerequisite for a string constant pool implementation is that the string object in Java is immutable, so that multiple variables can be safely guaranteed to share the same object. If a string object in Java is mutable, a reference operation changes the value of the object, and other variables are affected, which is obviously unreasonable.
Reference or Object
The most common issue is the time reference or object that is stored in a string constant pool. The string constant pool holds an object reference, not an object. In Java, objects are created in heap memory.
Update verification, I received a lot of comments are also discussed this issue, I have simply verified. Verifying the Environment
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)
Verification idea: The following Java program reads a video file size 82M, intern operation in string form.
22:01:17-androidyue~/videos$ LL-LH | grep why_to_learn.mp4
-rw-rw-r--. 1 androidyue androidyue 82M Oct 2013 Why_to_learn.mp4
Validating code
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 the heap memory for a permanent generation, it is applied before Java8. We validate by setting a permanent surrogate for a very small value. If a string object exists in a string constant pool, then the Java.lang.OutOfMemoryError PermGen space error must be thrown.
java-xx:permsize=6m Testmain ~/videos/why_to_learn.mp4
Running the proof program does not throw oom, in fact this can not be a good proof of the stored object or reference.
But the actual content object char[], which at least proves the string, is not stored in a string constant pool. In this case, it is not so important that the string constant pool store the string object or the reference to the string object. But individuals still tend to be stored as references.
Disadvantages
The benefit of a string constant pool is to reduce the creation of the same content string and save memory space.
If you want to say the drawbacks, it is to sacrifice the CPU time to change space. CPU computing time is primarily used to find references to objects that have the same content in a string constant pool. But its internal implementation is Hashtable, so the computational cost is low.
GC Recycle?
Because the string constant pool holds a reference to the shared string object, does that mean that the objects cannot be recycled?
The objects shared in the first question are generally small. As far as I'm aware, this problem does exist in earlier versions, but with the introduction of weak references, this problem should not be present.
On this issue, you can specifically understand 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 in the United States of California, we do not want to create a string object such as millions, we can use intern only in memory to keep a copy. For more in-depth understanding of intern, please refer to the in-depth analysis of String#intern.
There are always exceptions?
Do you know the following code that creates a few string objects that hold several references in a string constant pool?
String test = "a" + "B" + "C";
The answer is to create only one object, and only one reference is saved in the constant pool. We can tell by using JAVAP decompile.
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, in fact, during compilation, these three literal quantities have been synthesized one. This is actually an optimization that avoids the creation of extra string objects and no string concatenation problems. For string concatenation, you can view Java details: concatenation of strings.
Above is the Java string constant pool of data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!