Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the intern method in Java String

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge points about how to use the intern method in Java String. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Introduction to constant Pool

There are eight basic types and a relatively special type String in the JAVA language. These types provide a concept of constant pooling (in the method area) in order to make them faster and save memory during the run. Constant pools are similar to a cache provided at the JAVA system level. The eight basic types of constant pools are coordinated by the system, and the constant pools of String type are special.

There are two main ways to use the constant pool of String:

String objects declared directly in double quotes are stored directly in the constant pool.

If it is not a String object declared in double quotes, you can use the intern method provided by String to put it in the constant pool.

Introduction to intern method (JDK7)

Prototype: public native String intern ()

Description:

Query whether the current string exists from the string constant pool (determined by equals).

If present, returns a string reference in the constant pool.

If it does not exist, save the String object reference to the constant pool and return a reference to the String object.

Return value: all references to the string constant pool corresponding to the return String variable.

Example

Package com.example; public class Demo {public static void main (String argv []) {String s = "test"; System.out.println (s = = s.intern ());}}

JDK6 and before: output false

JDK7 and after: output true

Principle (JDK6 and JDK7)

The origin of the string in the constant pool

JDK6 and previous calls to String.intern ()

If there is one in the constant pool, a reference to the string in the constant pool is returned

If not in the constant pool, copy an object and put it in the constant pool (permanent generation); the return value is a reference to the corresponding string instance in the constant pool (permanent generation).

JDK7 and later call String.intern ()

If there is one in the constant pool, a reference to the string in the constant pool is returned

If not in the constant pool, copy a reference and put it in the constant pool (heap); (JDK1.7 moved the String constant pool from the Perm area to the Java Heap area)

Routine test

Routine 1:

Package org.example.a; public class Demo {public static void main (String argv []) {String S1 = new String ("1"); s1.intern (); String S2 = "1"; System.out.println (S1 = = S2); String S3 = new String ("1") + new String ("1"); s3.intern (); String S4 = "11" System.out.println (S3 = = S4);}}

Result

Jdk6:false false

Jdk7:false true

Jdk8:false true

Routine 2:

Package org.example.a; public class Demo {public static void main (String argv []) {String S1 = new String ("1"); s1.intern (); String S2 = "1"; System.out.println (S1 = = S2); String S3 = new String ("1") + new String ("1"); String S4 = "11"; s3.intern () System.out.println (S3 = = S4);}}

There is an exchange in the second part of the above code.

Result

Jdk6:false false

Jdk7:false false

Jdk8:false false

Routine analysis

In the following figure: the green line represents the content point of the String object. The red line indicates that the address points to.

Jdk1.6

Analysis of routine 1 and routine 2

As shown in the image above. First of all, let's talk about the situation in jdk6. All the above prints in jdk6 are false, because the constant pool in jdk6 is placed in the Perm area, and the Perm area is completely separate from the normal JAVA Heap area. As mentioned above, if the string is declared in quotation marks, it will be generated directly in the string constant pool, while the String object from new is placed in the JAVA Heap area. So it's definitely different to compare the object address of a JAVA Heap area with the object address of the string constant pool, and it doesn't matter even if you call the String.intern method.

Jdk1.7

In Jdk6 and previous versions, the constant pool of strings is placed in the Perm area of the heap, and the Perm area is a static area, which mainly stores some information about loading classes, constant pools, method fragments, and so on. The default size is only 4m. Once a large number of intern is used in the constant pool, java.lang.OutOfMemoryError:PermGen space errors will occur. In the jdk7 version, the string constant pool has been moved from the Perm section to the normal Java Heap area. Why to move, the Perm area is too small is one of the main reasons, of course, it is reported that jdk8 has directly cancelled the Perm area, and a new meta-area has been created. It should be that jdk developers think that the Perm area is no longer suitable for the current development of JAVA. The string constant pool is moved to the JAVA Heap area, and now explain why the above print results are available.

Analysis of routine 1

1.String S1 = new String ("1")

Analysis: this line of code generates two objects (the "1" in the constant pool and the string object in JavaHeap). S.intern (); the S1 object looks in the constant pool and finds "1" already in the constant pool.

At this point S1 points to a string object in Java Heap.

2.String S2 = "1"

Analysis: this line of code generates a reference to S2 that points to the "1" object in the constant pool. The result is that S1 and S2 have different reference addresses.

3.String S3 = new String ("1") + new String ("1")

Analysis: this line of code generates two objects ("1" in the string constant pool and "11" pointed to by the S3 reference in Java Heap (there are two anonymous new String ("1") in the middle that we won't discuss).

At this point, S3 is a reference to the string object in Java Heap, the object content is "11", and there is no "11" object in the constant pool.

4.s3.intern ()

Analysis: this line of code puts the "11" string in S3 into the String constant pool, because the "11" string does not exist in the constant pool, so the general practice is to generate an "11" object in the constant pool as shown in the jdk6 diagram. The key point is that the constant pool in jdk7 is not in the Perm area, but in the heap. Instead of storing an object in the constant pool, you can store references in the heap directly. This reference points to the object referenced by S3. In other words, the reference address is the same.

At this point, S3 is a reference to the string object in Java Heap, and the object content is "11". At this point, there is an "11" object in the constant pool, which holds the S3 reference address.

5.String S4 = "11"

This line of code "11" is explicitly declared, so it is created directly in the constant pool, and it is found that the object already exists when it is created.

At this point: S4 = "11" object reference of constant pool = = reference of S3 reference object

Analysis of routine 2

String S1 = new String ("1")

S1.intern ()

String S2 = "1"

Analysis: s1.intern (); it doesn't matter if you put this sentence back, because the "1" object is already generated when the first line of code String s = new String ("1") is executed in the object pool. The following S2 declarations take address references directly from the constant pool. The reference addresses of S1 and S2 will not be equal.

String S3 = new String ("1") + new String ("1")

Analysis: this line of code generates two objects ("1" in the string constant pool and "11" pointed to by the S3 reference in Java Heap (there are two anonymous new String ("1") in the middle that we won't discuss).

At this point, S3 is a reference to the string object in Java Heap, the object content is "11", and there is no "11" object in the constant pool.

String S4 = "11"

Analysis: when S4 is declared, there is no "11" object in the constant pool. after execution, S4 is a reference to the "11" object in the constant pool.

S3.intern ()

Analysis: at this point, the "11" object in the constant pool already exists, there will be no operation, and S3 is still a reference to the String object in the heap. So S3! = S4

Application example package org.example.a; import java.util.Random; public class Demo {static final int MAX = 1000 * 10000; static final String [] arr = new String [MAX]; public static void main (String argv []) {Integer [] DB_DATA = new Integer [10]; Random random = new Random (10 * 10000); for (int I = 0; I < DB_DATA.length) Long +) {DB_ data [I] = random.nextInt ();} long t = System.currentTimeMillis (); for (int I = 0; I < MAX; iTunes +) {/ / arr [I] = new String (String.valueOf (DB_ data [I% DB_DATA.length])); arr [I] = new String (String.valueOf (DB_ Data [I% DB_DATA.length])). Intern () } System.out.println ((System.currentTimeMillis ()-t) + "ms"); System.gc ();}}

The above code is a demo code with two different statements, one that uses intern and one that does not use intern.

The running parameter is-Xmx2g-Xms2g-Xmn1500M

No need for intern

2160ms

Use intern

826ms

From the above results, we found that the code that did not use intern generated 1000W strings, taking up about 640m of space. The code using intern generates 1345 strings, occupying about 133k of the total space. In fact, only 10 strings are used in the observation program, so the difference should be exactly 100w times after accurate calculation. Although the examples are extreme, they do accurately reflect the huge space savings resulting from the use of intern.

Careful students will find that there is some increase in time after using the intern method. This is because every time in the program after using new String, and then intern operation time-consuming, this point if in the case of sufficient memory space is indeed unavoidable, but we usually use, memory space is certainly not infinite, do not use intern space to lead to jvm garbage collection time is far greater than this time. After all, it took 1000W of intern to add more than a second.

These are all the contents of the article "how to use the intern method in Java String". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report