Touch Java constant Pool

Source: Internet
Author: User

Java constant pool is a long-lasting topic, but also the interviewer's favorite, the title of a variety of, side dishes have already heard of the constant pool, this time a good summary.

Theory

It's a little bit awkward. JVM Virtual Memory Distribution:

The program counter is the JVM executes the program pipeline, holds some jump instruction, this is too advanced, the side dish does not understand.

The local method stack is the stack used by the JVM to invoke the operating system method.

The virtual machine stack is the stack used by the JVM to execute Java code.

The method area holds some constants, static variables, class information, etc., which can be understood as the storage location of the class file in memory.

The virtual machine heap is the heap used by the JVM to execute Java code.

The constant pool in Java is actually divided into two forms: a static constant pool and a run-time pool .

The so-called static constant pool, the constant pool in the *.class file, is a constant pool in a class file that contains not only string literals, but also classes, methods, and most of the space in the class file.

running A constant pool is a JVM virtual machine that, after completing the class mount operation, loads the constant pool in class file into memory and saves it in the method area , which is what we often call a const pool, which refers to the run-time pool in the method area.

Next we refer to some examples of the popular constant pools on the web, and then we explain them.

1String S1 = "Hello";2String s2 = "Hello";3String s3 = "Hel" + "Lo";4String S4 = "Hel" +NewString ("Lo");5String S5 =NewString ("Hello");6String s6 =S5.intern ();7String s7 = "H";8String s8 = "Ello";9String S9 = s7 +S8;Ten            OneSystem.out.println (S1 = = s2);//true ASystem.out.println (S1 = = S3);//true -System.out.println (S1 = = S4);//false -System.out.println (S1 = = S9);//false theSystem.out.println (S4 = = S5);//false -System.out.println (S1 = = S6);//true

First of all, in Java, the direct use of the = = operator, compared to two strings of the reference address, not the comparison content, compare the content please use String.Equals ().

S1 = = S2 This very good understanding, S1, S2 in the assignment, all use the string literal, white point, is to write the string directly to die, during the compilation, this literal will directly into the class file in the constant pool, so as to achieve reuse, loaded into the run-time pool, S1, S2 points to the same memory address, so it is equal.

S1 = = S3 This place has a hole, S3 although the dynamic splicing out of the string, but all the parts involved in the stitching is known literal, during the compilation, this splicing will be optimized, the compiler directly help you spell, so string s3 = "Hel" + "lo"; The class file is optimized to string s3 = "Hello", so S1 = = S3 is established.

S1 = = S4 Of course not equal, S4 although also splicing out, but the new string ("Lo") this part is not known literal, is an unpredictable part, the compiler will not be optimized, you must wait until run time to determine the results, combined with the string invariant theorem, The ghost knows where the S4 is assigned, so the address must be different. With a schematic diagram to clarify the idea:

S1 = = S9 is not equal, the truth is similar, although S7, S8 in the assignment when the string literal used, but stitching into S9, S7, S8 as two variables, are unpredictable, compiler is compiler, it is not possible when the interpreter, so do not optimize, wait until the run, S7, S8 The new string, the address in the heap is not deterministic and cannot be the same as the S1 address in the method area constant pool.

S4 = = S5 have no explanation, absolutely not equal, both are in the heap, but the address is different.

S1 = = S6 The two equals are entirely attributed to the Intern method, S5 in the heap, the content is Hello, the Intern method attempts to add the Hello string to the constant pool and returns its address in the constant pool, because the constant pool already has a Hello string, So the Intern method returns the address directly, whereas S1 points to the constant pool at compile time, so S1 and S6 point to the same address, equal.

At this point, we can draw three very important conclusions:

You must focus on the behavior of the compilation period to better understand the constant pool.

Constants in the run-time pool are basically derived from constant pools in each class file.

When the program runs, the JVM does not automatically add constants to the constant pool unless constants are manually added to the constant pool (such as calling the Intern method).

The above only refers to the string constant pool, in fact there are integer constant pool, floating-point constant pool and so on, but all the same, but the constant pool of numeric types can not manually add constants, the program starts constant pool constants are determined, such as the constant range in the integer constant pool: -128~ 127, only the number of this range can be used in a constant pool.

Practice

Having said so many theories, let's touch the real constant pool.

As mentioned earlier, there is a static constant pool in the class file, which is generated by the compiler to store the literal in the Java source file (this article focuses only on the literal), assuming we have the following Java code:

1 String s = "HI";

For the sake of convenience, it is so simple, yes! After compiling the code into a class file, open the class file in binary format with Winhex.

Briefly explain the structure of the class file, the first 4 bytes is the class file magic number, to identify this is a class file, white session point is the file header, both: CA FE BA be.

Followed by 4 bytes is the Java version number, here the version number is 34, because the author is compiled with JDK8, the version number and the JDK version of the high and low relative to the higher version can be compatible with the lower version, but the lower version cannot perform a high version. So, if one day the reader wants to know what the JDK version of someone else's class file is compiled with, you can look at these 4 bytes.

Next is the constant pool entrance, the entrance with 2 bytes to identify the constant pool constant number, in this case the value is 1 A, translated into decimal is 26, that is 25 constants, where the No. 0 constant is a special value, so there are only 25 constants.

Constant pools hold various types of constants, they all have their own type, and all have their own storage specifications, this article focuses only on string constants, string constants starting with 01 (1 bytes), and then using 2 bytes to record the length of a string, and then the actual contents of the string. In this case: 01 00 02 68 69.

The next thing to say about running a constant-time pool, because the run-time pool is in the method area, we can set the method area size by JVM parameters:-xx:permsize,-xx:maxpermsize, which indirectly limits the constant pool size.

Assume that the JVM startup parameter is:-xx:permsize=2m-xx:maxpermsize=2m, and then run the following code:

 1  //  2  list<string> List = new  Arraylist<string> ();  3  int< /span> i = 0;  5   While  (true  ) { 7  //  Manually add constants to the constant pool by intern method  Span style= "color: #008080;" >8  List.add (string.valueof (I++). Intern ());  9 } 

The program immediately throws: Exception in thread "main" Java.lang.outOfMemoryError:PermGen space exception. PermGen space is the method area, sufficient to illustrate the Chang in the method area.

In Jdk8, the method area is removed and replaced with the Metaspace region, so we need to use the new JVM parameter:-xx:maxmetaspacesize=2m, which is still running as above code, throws: Java.lang.OutOfMemoryError: Metaspace exception. Similarly, the run-time constant pool is divided in the Metaspace area. For specific information about the Metaspace area, please search the reader on your own.

All of the code in this article is tested under JDK7, JDK8, and other versions of the JDK may be slightly different, please explore by yourself.

References:deep understanding of Java Virtual Machines ——— JVM advanced features and best practices

Touch Java constant Pool

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.