On the storage location of string constants in Java

Source: Internet
Author: User

Before we tell you about this, we need some preliminary knowledge:

Java's memory structure we can look at it in two ways.

look from the perspective of an abstract JVM . Refer to the JVM specification for the relevant definitions: Chapter 2. The Structure of the Java Virtual machine

From this point of view, the Java memory structure contains the following sections: This section can be combined: JVM Introduction (more in-depth introduction)

1, the stack area: The compiler automatically allocates the release, after the concrete method executes, the system automatically frees the JVM memory resources.

The function has the value of saving local variables, including: 1. The value used to hold the base data type; 2. A reference to the instance object that holds the class. It can also be used to save the frame when the method is loaded.

2, heap area: generally by the programmer to allocate the release, the JVM does not periodically view this object, if there is no reference to this object is recycled.

It is used to store dynamically generated data, including new instances, arrays, etc. Note the objects that are created contain only the member variables that belong to them, and do not include member methods.

Because objects of the same class have their own member variables stored in their own heap, they share the methods of the class, and not every object is created to copy the member method one at a time.

3. Code Area : The binary code that stores the method in the program, and multiple objects share a region of code space.

4. Data area: static member used to store static definition.

5, Chang: The JVM maintains a constant pool for each loaded type, and the constant pool is an ordered set of constants used by this type. Includes direct constants (basic types, String) and symbolic references to other types, methods, and fields. The data in the pool is accessed through the same index as the array. Because a constant pool contains symbolic references to other types, methods, and fields for one type, Chang plays a central role in the dynamic linking of Java. A constant pool exists in the heap.

Roughly describes the memory allocation in Java

Second, from the perspective of the process on the operating system . Related definitions Please refer to the various operating system information, such as Linux, can refer to this simple introduction: Linux Processes explained (this aspect is generally less discussed, this article only to do a little introduction)

It is important to remember that the concept of the abstract JVM described by the JVM specification does not correspond to the actual implementation of one by one.

Let's take a look at some code examples and comments:

 Public classTeststringconstant { Public Static voidMain (String args[]) {//string constants, which are allocated in a constant pool, are optimized by the compiler, interned table//that is, when a string already exists, the same object is not created again, and the S2 is pointed directly to "Hello".String S1 = "Hello"; String S2= "Hello"; //new objects are allocated in the heap. S3 and S4 Although they point to the same string content, they are two different objects. //so = = The reference is different when it is compared, so it is not equalString s3 =NewString ("World"); String S4=NewString ("World"); System.out.println (S1= = s2);//trueSystem.out.println (s3 = = S4);//falseSystem.out.println (S3.equals (S4));//true//The equals method in string has been rewritten, comparing whether the content is equal.    }}

The compiler optimizations mentioned in the previous example code are described in more detail below. Take a look at the following example code:

class a {    private String a = "AA";      Public Boolean MethodB () {        = "BB";         Final String c = "CC";         return false ;    }}

The string Object "AA", "BB" is on the Java heap by the JVM specification, in the Hotspot VM implementation prior to JDK8 in PermGen, in the hotspot VM starting in JDK7 in the normal Java heap (rather than in PermGen); " CC "is the same if it exists, but it may not exist.

These string objects belong to "interned string". String is a Java object that must exist in the Java heap, as defined by the JVM specification, and interned string is no exception. Interned string in particular is that the JVM will have a stringtable with a interned string, ensuring that the same string object is not duplicated intern. (This is the compiler's optimization)

This stringtable how to implement the JVM specification is not specified, but usually it does not save the contents of the string object, but only to save a reference to the string object.

    • See the A, B, c variables from the JVM specification:

A variable is used as an object instance field of Class A, followed by an instance of a on the Java heap.

The b variable is on the Java thread stack as a local variable.

A c variable is a local variable, but because it has a final decoration and is initialized to a constant value, C is a constant. It may be optimized (there is no C variable), or it may be a local variable on the Java thread stack as B.

I believe you have a more vivid understanding of the allocation area of string constants and the memory allocation of Java.

Here are some of the relevant knowledge points to add and note:

1. distinguish what an instance is and what an object is. Class a= New Class (), at which point A is called an instance, not a is an object. The instance is in the stack, the object is in the heap, and the operation instance is actually manipulating the object indirectly through the pointer of the instance. Multiple instances can point to the same object.

2. data in the stack is not synchronized with data destruction in the heap. Once the method ends, the local variables in the stack are destroyed immediately, but the objects in the heap are not necessarily destroyed. Because there may be other variables that point to this object, it is destroyed only if there are no variables in the stack that point to the object in the heap, and it is not destroyed immediately, and can be destroyed when the garbage collection is scanned.

3. The above stacks, heaps, code snippets, data segments, and so on are all relative to the application. Each application corresponds to a unique instance of the JVM, and each JVM instance has its own area of memory that does not affect each other. And these memory areas are shared by all threads. The stacks and heaps mentioned here are concepts on the whole, and these stacks can be subdivided.

4. the member variables of a class vary in different objects and have their own storage space (the member variable is in the object in the heap). The method of the class is shared by all objects of the class, only one set, the method is pressed into the stack when the object is used, and the method does not consume memory.

    • See from the implementation of the hotspot VM:

When MethodB () is interpreted and executed, the input bytecode is executed, and since the implementation of JAVAC does not optimize the variable B, the call to MethodB () is bound to be in the local variable area of the Java thread stack, when the variable C exists in the byte code. It is also the same as B in the local variable area of the Java line stacks.

When MethodB () is JIT-compiled, the local variables B and C are not used, so they are JIT-compiled and disappear, and calling MethodB () does not allocate any space to the B or C variables on the stack.

I believe you have a more vivid understanding of the allocation area of string constants and the memory allocation of Java.

Here are some of the relevant knowledge points to add and note:

1. distinguish what an instance is and what an object is. Class a= New Class (), at which point A is called an instance, not a is an object. The instance is in the stack, the object is in the heap, and the operation instance is actually manipulating the object indirectly through the pointer of the instance. Multiple instances can point to the same object.

2. data in the stack is not synchronized with data destruction in the heap. Once the method ends, the local variables in the stack are destroyed immediately, but the objects in the heap are not necessarily destroyed. Because there may be other variables that point to this object, it is destroyed only if there are no variables in the stack that point to the object in the heap, and it is not destroyed immediately, and can be destroyed when the garbage collection is scanned.

3. The above stacks, heaps, code snippets, data segments, and so on are all relative to the application. Each application corresponds to a unique instance of the JVM, and each JVM instance has its own area of memory that does not affect each other. And these memory areas are shared by all threads. The stacks and heaps mentioned here are concepts on the whole, and these stacks can be subdivided.

4. the member variables of a class vary in different objects and have their own storage space (the member variable is in the object in the heap). The method of the class is shared by all objects of the class, only one set, the method is pressed into the stack when the object is used, and the method does not consume memory.

For the related additions to string:

The modification to the string is actually a new StringBuilder and calls the Append method, and then calls ToString to return a fresh string.

(Note: The Append method does not have new objects.)

However, the JVM optimizes strings, such as:

String str = "I" + "Love" + "Java"

The string can be confirmed at compile time, so the compiler will simply stitch it into a string in a constant pool: "I love Java"

But if the code is the following:

String a = "I"; String B = "Love"; String C = "Java"; String str = a + B + C;

Then it is only when the runtime is able to determine what STR is ultimately, and the compiler does not optimize it, but rather StringBuilder the string change.

Note, however, that if you add the final keyword to a, B, and C here, the compiler will be able to optimize it. We can do one of the following tests:

 Public classfoo{ Public Static voidMain (string[] args) {String a= "I"; String b= "Love"; String C= "Java"; FinalString a1 = "I"; FinalString B1 = "Love"; FinalString C1 = "Java"; String Str= A + B +C; String str1= A1 + B1 + C1;//equals to str1 = "I" + "Love" + "Java"String str2 = "I" + "Love" + "Java"; System.out.println (str= = "I love java");//Output FalseSystem.out.println (str1 = = "I love java");//Output TrueSystem.out.println (str2 = = "I love java");//Output TrueSystem.out.println (A + "love" + "java" = = "I love java");//Output FalseSYSTEM.OUT.PRINTLN (A1 + "Love" + "java" = = "I love java");//Output True    }}

Note:

The difference between StringBuilder and StringBuffer:

StringBuffer is thread-safe; StringBuilder is non-thread safe.

Because Stingbuffer is locked on the basis of StringBuilder, and locking is a heavyweight operation, it needs to be implemented by invoking the operating system kernel.

More time consuming.

So on efficiency: StringBuilder > StringBuffer

On the storage location of string constants in Java

Related Article

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.