Java String # intern () Memory Model
The String constant pool is a fixed-size HashMap. The default number of buckets is 1009. The default value increases from Java7u40 to 60013. In Java 6, the string constant pool is placed in the Perm space. from Java 7, The String constant pool is moved to the Heap space. Next, we will test the program to check the memory allocation of the String constant pool in Java 6 and Java 7 versions.
Test procedure
- public class StringPoolTest {
-
- public void testStringPoolWithLongString(){
- long i=0;
- while(true){
- String longString = "This is a very long string, very very long string to test the gc behavior of the string constant pool"+i;
- longString.intern();
- i++;
- }
- }
-
- public static void main(String[] args){
- StringPoolTest stringPoolTest = new StringPoolTest();
- stringPoolTest.testStringPoolWithLongString();
- }
- }
The test program is very simple. It is an endless loop. in the loop, the variable I is used to create a unique string, and then the main function is used to start the program.
Java 6
We use the Jdk1.6.0 _ 29 version to run the program. Open Java VisualVM monitoring and we can see that GC occurs continuously in the Perm area. From this conclusion, although the String constant pool is placed in the Perm space, however, when the Perm space is close to full, JVM recycles useless strings in the String constant pool.
Java 7
Next, we switch to Jdk1.7.0 _ 67 and re-run the program. We can see that the memory allocation curve in the Perm area is smooth and there is no memory allocation.
However, in Heap space, new objects are constantly generated, and GC is continuously triggered.
Conclusion
Since the Perm area is limited in size and usually only dozens of MB, we do not recommend that you use String in Java 6. intern (), this article string-intern-in-java-6-7-8 performance tests show that using intern () in large quantities under java 6 will lead to a significant reduction in application performance, OOM errors may also occur. However, from Java 7, The String constant pool is moved to the Heap space. The size of the Heap space is only subject to the actual memory size of the machine. Therefore, the String is used in Java 7. intern () can more effectively reduce the memory usage of repeated String objects.