Memory Allocation and variable storage location (heap, stack, method zone constant pool, method zone static zone), constant static

Source: Internet
Author: User

Memory Allocation and variable storage location (heap, stack, method zone constant pool, method zone static zone), constant static

Source: http://www.cnblogs.com/protected/p/6419217.html

Intrusion and deletion!

 

When the program is running, data can be saved in six places:

1. Register: This is the fastest storage region, because it is located in a different place from all other storage methods: Inside the processor. However, the number of registers is very limited, so the registers are allocated by the compiler as needed. We have no direct control over this, and it is impossible to find any trace of the Register in our program.
2. STACK:Stores basic data and object references, but the object itself is not stored in the stack, but in the heap (new object ).Resident in the regular RAM (Random Access to memory) area. However, you can use its "Stack pointer" to obtain direct processing support. If the stack pointer moves downward, a new memory is created. If it moves upward, the memory is released. This is a fast and efficient data storage method, second only to registers. When creating a program, the java compiler must accurately know the "length" and "time of existence" of all data stored in the stack ". This is because it must generate the corresponding code to move the pointer up and down. This restriction undoubtedly affects the flexibility of the program. Although some java data must be stored in the stack, especially the object handle, java objects are not put in it.
3. Heap:Store data generated with new.A general-purpose Memory Pool (also in the RAM region) that stores java objects. Different from Stack: the most attractive thing about "memory Heap" or "Heap" is that the compiler does not have to know how much storage space is allocated from the heap, you do not need to know how long the stored data will stay in the heap. Therefore, it is more flexible to store data in a heap. To create an object, you only need to use the new command to compile the code that you encounter. When the code is executed, data is automatically saved in the heap. Of course, in order to achieve this flexibility, it will inevitably pay a certain price: It will take longer to allocate storage space in the heap.
4. Static domain:Static members that are stored in objects.Here "static" refers to "in a fixed position ". During the running of the program, the static storage data will be waiting for calling at any time. The static keyword can be used to indicate that a specific element of an object is static. However, java objects are never placed in static buckets.
5. Constant pool:Store constants.Constant values are usually placed directly inside the program code. This is safe. Because they will never change and some constants require strict protection, you can consider placing them in read-only memory (ROM ).
6. Non-RAM storage: Permanent storage space such as hard disk. If the data is completely independent from a program, the program may still exist when it is not run and is out of the control scope of the program. Two major examples are "stream object" and "fixed object ". For stream objects, objects are converted into byte streams, which are usually sent to another machine. For fixed objects, objects are stored on disks. Even if the program stops running, they can remain in their own State. A particularly useful technique for these types of data storage is that they can be stored in other media and can even be restored to common, RAM-based objects as needed.

 

Stack in Java Memory Allocation

Variable data of some basic types defined in functions and referenced variables of objects are allocated in the function stack memory.

When a variable is defined in a code block, Java allocates memory space for the variable in the stack. After the variable exits the scope, java will automatically release the memory space allocated for the variable, and the memory space can be used for another use immediately. The data size and lifecycle in the stack can be determined. When no reference points to the data, the data will disappear.

  1. Each thread contains a stack zone. Only objects of the basic data type and reference (not objects) of custom objects are stored in the stack zone.
2. Data in each stack (original type and Object Reference) are private and cannot be accessed by other stacks.
3. the stack is divided into three parts: basic variable zone, execution environment context, and operation instruction zone (storing operation instructions ).

 

Heap in Java Memory Allocation

Heap memory is used to store objects and arrays created by new. The memory allocated in the heap is managed by the Java Virtual Machine's automatic garbage collector.

After an array or object is generated in the heap, you can define a special variable in the stack so that the value of this variable in the stack is equal to the first address of the array or object in the heap memory, the variable in the stack becomes the referenced variable of the array or object. The referenced variable is equivalent to an array or an object name. Later, you can use the referenced variable in the stack in the program to access the array or object in the heap. The referenced variable is equivalent to an array or object name.

The referenced variable is a common variable. It is assigned to the stack during definition. The referenced variable is released after the program runs out of its scope. Arrays and objects are allocated in the heap. Even if the program runs outside the code block where the new statement is used to generate arrays or objects, the memory occupied by arrays and objects is not released, arrays and objects become junk only when no referenced variable points to it. They cannot be used, but still occupy the memory space, the garbage collector collects (releases) the garbage collector at an uncertain time ). This is also the reason why Java accounts for memory usage.

  1. All objects are stored, and each object contains information about the corresponding class. (The purpose of class is to get operation instructions)
2. Only one heap in the jvm is shared by all threads. The jvm does not store basic types and object references, but only stores the object itself.

In fact, the variables in the stack point to the variables in the heap memory. This is the pointer in Java!

 

Stack and stack

The Java heap is a runtime data zone and class (the object allocates space from it. These objects are created using commands such as new, newarray, anewarray, and multianewarray. They do not need program code to be explicitly released. The heap is responsible for garbage collection. The advantage of the heap is that the memory size can be dynamically allocated, and the lifetime does not have to be told in advance because the heap dynamically allocates memory at runtime, the Java Garbage Collector automatically collects the unused data. However, the slow access speed is due to the need to dynamically allocate memory during runtime.

The advantage of stack is that the access speed is faster than that of stack, second only to register, and stack data can be shared. However, the disadvantage is that the data size and lifetime in the stack must be fixed, and there is a lack of flexibility. The stack mainly stores some basic types of variable data (int, short, long, byte, float, double, boolean, char) and object handle (reference ).

A very important feature of stacks is that data in stacks can be shared. Suppose we define both:

Java code

1 int a = 3;3 int b = 3;

 

The compiler first processes int a = 3. First, it creates a reference with the variable a in the stack, and then finds whether the value 3 in the stack exists. If no value is found, store 3 and point a to 3. Then process int B = 3. After the referenced variable of B is created, B is directed to 3 because there is already 3 in the stack. In this way, both a and B point to 3 at the same time.

At this time, if a is set to 4 again, the compiler will re-search whether there are 4 values in the stack. If not, it will store 4 and make a point to 4; if yes, direct a to this address. Therefore, changing the value of a does not affect the value of B.

Note that the sharing of data is different from the sharing of two objects pointing to one object at the same time, because the modification of a does not affect B, which is completed by the compiler, it facilitates space saving. A variable referenced by an object modifies the internal state of the object, which affects the variable referenced by another object.

Java code

1 int i1 = 9;  2 int i2 = 9;  3 int i3 = 9;   4 public static final int INT1 = 9;  5 public static final int INT2 = 9;  6 public static final int INT3 = 9; 

For member variables and local variables: The member variables are the external methods, the variables defined inside the class, and the local variables are the variables defined inside the method or statement block. Local variables must be initialized.
The formal parameter is a local variable, and the data of the local variable is stored in the stack memory. The local variables in the stack memory disappear as the method disappears.
The member variables are stored in the heap object and are recycled by the garbage collector.
Run the following code:
Java code

1 class BirthDate {2 private int day; 3 private int month; 4 private int year; 5 public BirthDate (int d, int m, int y) {6 day = d; 7 month = m; 8 year = y; 9} 10 // omit get, set Method ......... 11} 12 13 public class Test {14 public static void main (String args []) {15 int date = 9; 16 Test test = new Test (); 17 test. change (date); 18 BirthDate d1 = new BirthDate (1970, 1234); 19} 20 public void change1 (int I) {21 I =; 22} 23}

 


For the above Code, date is a local variable, and I, d, m, and y are all member variables with the form parameters as local variables, day, month, and year. The following describes the changes in code execution:
1. Run the main method: int date = 9;
Date local variables, basic types, references, and values all exist in the stack.
2. Test test = new Test ();
Test is an object reference. It exists in the stack and the object (new Test () exists in the heap.
3. test. change (date );
I is a local variable and the reference and value exist in the stack. After the method change is executed, I disappears from the stack.
4. BirthDate d1 = new BirthDate (1970 );
D1 is an object reference and is in the stack. The object (new BirthDate () is in the heap, where d, m, and y are local variables stored in the stack, and their types are the basic types, so their data is also stored in the stack. Day, month, and year are member variables, which are stored in the heap (new BirthDate ). After the BirthDate constructor is executed, d, m, and y will disappear from the stack.
5. After the main method is executed, the date variables, test, and d1 references will disappear from the stack. new Test () and new BirthDate () will wait for garbage collection.

Static domain

 Method Area:
1. The static zone is shared by all threads like the heap. The method area contains all the class and static variables.
2. The method area contains always unique elements in the entire program, such as class and static variables.

Java does not have the concept of static variables. Do not believe that you define a static int I = 0 in the method. java only has static member variables. It belongs to the attributes of the class. Where is it? In jvm, it is translated into a method area (it can also be called a static domain ). Virtual Machine architecture: Stack, method area, local method stack, pc register. The method area stores a class template, and the heap is a class instance. Stack is generally used for function compute. All you need to do is find the books at the bottom of the computer. The data in the stack will not be stored after the function is executed. This is why local variables are the same every time. Even after adding one to him, the next time the function is executed, it is still the same.

Constant pool)

A constant pool refers to some data that is determined during the compilation period and stored in the compiled. class file.

Besides containing the basic types (such as int and long) defined in the Code and the constant values (final) of the object type (such as String and array) it also contains some symbolic references that appear in the form of text, such:

◆ Full qualified names of classes and interfaces;

◆ Field name and descriptor;

◆ Method and name and descriptor.

If it is already created during the compilation period (defined using double quotation marks), it will be stored in the constant pool. If it is confirmed by the runtime (new), it will be stored in the heap. For strings with equal equals, there is always only one copy in the constant pool, and there are multiple copies in the heap.

String is a special packaging data. Available:

Java code

String str = new String("abc");String str = "abc";

 

The first method is to use new () to create an object, which is stored in the heap. Each call creates a new object. The second is to first create a String class object reference variable str in the stack, and then use the symbol reference to find out if there is "abc" in the String constant pool. If there is no, store "abc" in the String constant pool and point str to "abc". If "abc" already exists, direct str to "abc ".

Use the equals () method to compare the values in a class. Use the = method to test whether the references of the two classes point to the same object. The example below illustrates the above theory.

Java code

String str1 = "abc";String str2 = "abc";System.out.println(str1==str2); //true

 

It can be seen that str1 and str2 point to the same object.

Java code

String str1 =new String ("abc");String str2 =new String ("abc");System.out.println(str1==str2); // false

 

The new method is used to generate different objects. Each time one is generated.

Therefore, the second method is used to create multiple "abc" strings, and only one object exists in the memory. this method is advantageous and saves memory space. at the same time, it can improve the program running speed to a certain extent, because the JVM will automatically decide whether to create a new object based on the actual situation of the data in the stack. For the code of String str = new String ("abc");, a new object is created in the heap, regardless of whether the String value is equal, whether it is necessary to create a new object, this increases the burden on the program.

On the other hand, note that when we use a format such as String str = "abc"; to define a class, we always take it for granted that the String class Object str is created. Worry trap! The object may not be created! Instead, it may only point to a previously created object. Only by using the new () method can a new object be created every time.

 

Several examples of String constant pool problems

Example 1:

Java code

String s0="kvill";String s1="kvill";String s2="kv" + "ill";System.out.println( s0==s1 );System.out.println( s0==s2 );

 

Result:

True

True

Analysis:First, we need to know that Java will ensure that a String constant has only one copy.

Because "kvill" in s0 and s1 in the example are string constants, they are determined during the compilation period, so s0 = s1 is true; "kv" and "ill" are both string constants. When a character string is connected by multiple string constants, it must be a String constant, so s2 is also parsed as a String constant during compilation, so s2 is also a reference of "kvill" in the constant pool. So we get s0 = s1 = s2;

Example 2:

Example:

Java code

String s0="kvill";String s1=new String("kvill");String s2="kv" + new String("ill");System.out.println( s0==s1 );System.out.println( s0==s2 );System.out.println( s1==s2 );

 

Result:

False

False

False

Analysis:The String created with new String () is not a constant and cannot be determined during the compilation period. Therefore, the strings created with new String () are not placed in the constant pool and they have their own address space.

S0 is still an application of "kvill" in the constant pool. s1 is a reference of the new object "kvill" created at runtime because it cannot be determined during the compilation period, s2 is also an application that creates the "kvill" object because it has a new String ("ill") in the second half and cannot be determined during the compilation period; if you understand this, you will know why this result is obtained.

Example 3:

Java code

 1 String a = "a1"; 2 String b = "a" + 1; 3 System.out.println((a == b)); //result = true  4  5 String a = "atrue"; 6 String b = "a" + "true"; 7 System.out.println((a == b)); //result = true  8  9 String a = "a3.4";10 String b = "a" + 3.4;11 System.out.println((a == b)); //result = true

 

Analysis: JVM connects the "+" Number of string constants. During the program compilation period, the JVM optimizes the "+" connection of the constant string to the connected value, take "a" + 1 as an example. After the compiler is optimized, it is already a1 in the class. The value of its String constant is determined during compilation, so the final result of the above program is true.

Example 4:

Java code

String a = "ab";String bb = "b";String b = "a" + bb;System.out.println((a == b)); //result = false

 

Analysis: JVM references strings. Due to the existence of string references in the "+" connection of strings, the referenced values cannot be determined during program compilation, that is, "a" + bb cannot be optimized by the compiler. It is dynamically allocated only during the running period and assigned the new connection address to B. Therefore, the result of the above program is false.

Example 5:

Java code

String a = "ab";final String bb = "b";String b = "a" + bb;System.out.println((a == b)); //result = true

 

Analysis: The only difference from [4] Is that the bb string is decorated with final. For final modified variables, it is parsed as a local copy of a constant value during compilation and stored in its own constant pool or embedded in its byte code stream. Therefore, "a" + bb "and" a "+" B "have the same effect. Therefore, the result of the above program is true.

Example 6:

Java code

String a = "ab";final String bb = getBB();String b = "a" + bb;System.out.println((a == b)); //result = falseprivate static String getBB() {      return "b";   }

 

Analysis: JVM cannot determine the value of bb in string reference during compilation. Only after the method is called during the runtime, dynamically connect the return value of the method with "a" and assign the address B. Therefore, the result of the above program is false.

 

String is immutable.

The above example shows that:

String s = "a" + "B" + "c ";

It is equivalent to String s = "abc ";

String a = "";

String B = "B ";

String c = "c ";

String s = a + B + c;

This is different. The final result is equal:

Java code

StringBuffer temp = new StringBuffer();temp.append(a).append(b).append(c);String s = temp.toString();

 

From the above analysis results, it is not difficult to infer the cause of the inefficiency of the String using the join operator (+), such as the Code:

Java code

 1 public class Test { 2  3      public static void main(String args[]) { 4  5        String s = null; 6  7        for(int i = 0; i < 100; i++) { 8  9            s += "a";10       }11    } 12 }

 

Every time you do the plus sign (+), a StringBuilder object is generated and then thrown away after append. When the next loop arrives, A StringBuilder object is generated again, and then the append string is generated. The loop ends until the end. If we directly use the StringBuilder object for append, we can save N-1 time to create and destroy objects. Therefore, for applications that require string connection in a loop, the append operation is generally performed using the StringBuffer or StringBulider object.

Because of the immutable nature of the String class, we need to talk a lot more about it. We only need to know that once the String instance is generated, it will not change any more. For example: string str = "kv" + "ill" + "" + "ans"; there are four String constants, first, "kv" and "ill" generate "kvill" in memory, and then "kvill" and "generate" kvill "in memory, finally, the "kvill ans" is generated, and the address of this String is assigned to str, because the String's "immutable" produces many temporary variables, this is the reason why StringBuffer is recommended, because StringBuffer can be changed.

 

Usage and understanding of final in String

Java code

Final StringBuffer a = new StringBuffer ("111 ");

Final StringBuffer B = new StringBuffer ("222 ");

A = B; // This sentence cannot be compiled

Final StringBuffer a = new StringBuffer ("111 ");

A. append ("222"); // compiled

It can be seen that final is only valid for the referenced "value" (that is, the memory address), which forces the reference to point only to the object initially pointed to. changing its direction will lead to compilation errors. Final is not responsible for the changes to the objects it points.

 

Summary

  The stack stores local variable data of some original data types and references of objects (String, array. Object, etc.) but does not store object content.

Heap stores the objects created with the new keyword.

A string is a special packaging class. Its reference is stored in the stack, and the object content must be determined according to the creation method (constant pool and heap ). some have been created in the compilation phase and stored in the regular string pool, while others are created during runtime. store the new keyword in the heap.

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.