Heap, stack, and constant pool of Java memory allocations

Source: Internet
Author: User

Excerpt from http://www.cnblogs.com/SaraMoring/p/5687466.html

Java memory allocations mainly include the following areas:

1. Register: We have no control in the program

2. Stack: A reference to the basic type of data and objects, but the object itself is not stored in the stack, but is stored in the heap

3. Heap: Storing data generated with new

4. Static domain: Static members stored in the object defined with static

5. Constant pool: Storing constants

6. Non-RAM (random access memory) storage: Permanent storage space such as hard disk

*****************************************************************

Stacks in Java memory allocation

Some basic types of variable data and object reference variables that are defined in the function are allocated in the function's stack memory. When a variable is defined in a block of code, Java allocates memory space for the variable in the stack, and when the variable exits the scope, Java automatically frees the memory space allocated for the variable, and the memory space is immediately available for another use.

Java Memory points the stack in the match

Heap memory is used to hold objects and arrays created by new. The memory allocated in the heap is managed by the automatic garbage collector of the Java Virtual machine.

After generating an array or an object in the heap, you can also define a special variable in the stack that is equal to the first address of the array or object in the heap memory, and this variable in the stack becomes the reference variable of the array or object. A reference variable is a name that is an array or an object, and you can use reference variables from the stack to access the arrays or objects in the heap later in your program. A reference variable is equivalent to a name that is an array or an object.

A reference variable is a normal variable that is allocated in the stack when defined, and the reference variable is freed after the program runs outside its scope. While the array and the object itself are allocated in the heap, the memory occupied by the array and the object itself is not freed when the program runs beyond the block of code that uses new to produce the array or object's statement, and the array and object become garbage when no reference variable points to it, not in use, but still occupy memory space. The garbage collector takes off (releases) at a later indeterminate time. This is why the Java comparison accounts for memory.

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

Chang (Constant Pool)

Chang refers to some data that is determined at compile time and is saved in the compiled. class file. In addition to the constant values (final) that contain the various basic types defined in the code (such as int, long, and so on) and object types (such as strings and arrays), there are also some symbolic references that appear as text, such as:

    1. The fully qualified name of the class and interface;
    2. The name and descriptor of the field;
    3. Methods and names and descriptors.

The virtual machine must maintain a constant pool for each mounted type. A constant pool is an ordered set of constants used by that type, including direct constants (String,integer and floating point constants), and symbolic references to other types, fields, and methods.

For a string constant, its value is in a constant pool. The Chang in the JVM exists as a table in memory, and for string types there is a fixed-length constant_string_info table for storing literal string values, note that the table stores only literal string values and does not store symbol references. In this case, there should be a clearer understanding of where the string values in the constant pool should be stored.

When the program executes, the constant pool is stored in the method area, not the heap.

Heap and Stack

The Java heap is a run-time data area in which objects allocate space. These objects are established through directives such as new, NewArray, Anewarray, and Multianewarray, and they do not require program code to be explicitly released. Heap is responsible for garbage collection, the advantage of the heap is the ability to dynamically allocate memory size, the lifetime does not have to tell the compiler beforehand, because it is at runtime to allocate memory dynamically, Java garbage collector will automatically take away these no longer use data. However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time.

The advantage of the stack is that the access speed is faster than the heap, after the register, the stack data can be shared. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. The stack mainly contains some basic types of variable data (int, short, long, byte, float, double, Boolean, char) and object handle (reference).

******************************************************************

Here we are primarily concerned with stacks, heaps, and constant pools, which can be shared for objects in stacks and constant pools, and not for objects in the heap. The data size and life cycle in the stack can be determined, and the data disappears when no references point to the data. The garbage collector is responsible for the collection of objects in the heap, so the size and life cycle do not need to be determined and have great flexibility.

String memory allocation:

For strings, references to objects are stored in the stack, and if the compilation period has been created (defined directly in double quotes), it is stored in a constant pool, which is stored in the heap if the run-time (new) is determined. For a string equal to equals, there is always only one copy in the constant pool, with multiple copies in the heap.

such as the following code:

        String S1 = "China";        String s2 = "China";        String s3 = "China";        String ss1 = new String ("China");        String ss2 = new String ("China");        String ss3 = new String ("China");

Here is an explanation of the yellow 3 arrows, for a string created by new (assuming "China"), will first go to the constant pool to find if there is already a "China" object, if not a constant pool to create this string object, and then create a constant pool in the heap in this "China" The Copy object of the object.

This is also the Youdao interview question: strings=newstring ("xyz"), how many objects? One or two, if there is no "xyz" in the constant pool, it is two.

The constant pool that exists in the. class file is loaded by the JVM at run time and can be expanded. The Intern () method of string is a method of extending a constant pool, and when a string instance str calls the Intern () method, Java looks for a constant pool with the same Unicode string constant, if any, and returns its reference, if not, Adds a string in the constant pool that is Unicode equals STR and returns its reference

The following code:

        String s0= "Kvill";           String S1=new string ("Kvill");           String S2=new string ("Kvill");           System.out.println (S0==S1);             S1.intern ();           S2=s2.intern (); The reference to "Kvill" in the constant pool is assigned to S2           System.out.println (S0==S1);           System.out.println (S0==s1.intern ());           

Output Result:

False
False
True
True

A few examples of string constant pooling problems:

"1"
String a = "AB"; String BB = "B"; String B = "a" + BB; System.out.println ((A = = b)); result = False "2"
String a = "AB"; Final String bb = "B"; String B = "a" + BB; System.out.println ((A = = b)); Result = True "3"
String a = "AB"; Final String bb = GETBB (); String B = "a" + BB; System.out.println ((A = = b)); result = False private static String GETBB () { return "B";

Analysis:

"1", the JVM for the string reference, because in the string "+" connection, there is a string reference exists, and the value of the reference in the program compilation period is not determined, that "a" + BB can not be optimized by the compiler, only during the program run time to dynamically allocate and the new address after the connection to B. So the result of the above program is also false.

The only difference between "2" and "1" is that the BB string is added to the final decoration, and for a final modified variable, it is stored in its own constant pool or embedded in its byte stream at compile time by a local copy that is parsed to a constant value. So at this point the "a" + BB and "a" + "B" effect is the same. Therefore, the result of the above program is true.

"3" JVM for the string reference BB, its value in the compilation period can not be determined, only after the program run time call method, the return value of the method and "a" to dynamically connect and assign the address to B, so the result of the above program is false.

Conclusion:

A string is a special wrapper class whose reference is stored in the stack, and the object content must be set differently (Chang and heap) depending on how it was created. Some compile time has been created, stored in a string constant pool, and some runtime is created. Use the new keyword to store in the heap.

Allocation of variables and constants of the underlying type in memory

For variables and constants of the underlying type, variables and references are stored in the stack, and constants are stored in the constant pool.

such as the following code:

        int i1 = 9;        int i2 = 9;        int i3 = 9;        Final int INT1 = 9;        Final int INT2 = 9;        Final int INT3 = 9;

The compiler processes int i1 = 9 First, it creates a reference in the stack with a variable of i1, and then finds out if there is a value of 9 in the stack, and if it does not, it stores 9 and then points the I1 to 9. the int i2 = 9 is then processed, and after the I2 reference variable is created, the i2 is pointed directly to 9 because there is already 9 in the stack. In this way, the I1 and I2 both point to 9. Finally i3 points also to this 9.

Allocation of member variables and local variables in memory

For member variables and local variables: member variables are external to the method, variables defined internally by the class, and local variables are variables defined inside a method or statement block. Local variables must be initialized. The formal parameter is a local variable, and the data for the local variable exists in the stack memory. Local variables in the stack memory disappear as the method disappears.   Member variables are stored in objects in the heap and are collected by the garbage collector. such as the following code:

Class BirthDate {    private int day;    private int month;    private int year;    Public BirthDate (int d, int. m, int y) {Day        = D;        month = m;        Year = y;    }    Omit the Get,set Method ...} public class Test {public    static void Main (String args[]) {        int date = 9;        Test test = new test ();        Test.change (date);        BirthDate D1 = new BirthDate (7, 7, 1970);    }    public void Change (int i) {        i = 1234;    }}

For this code, date is a local variable, i,d,m,y is a local variable, and Day,month,year is a member variable. The following analysis of the code execution time changes:

    1. The main method begins execution: int date = 9; Date local variables, underlying types, references, and values are present in the stack.
    2. Test test = new test (), test is the object reference, 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. When the method change execution is complete, I will disappear from the stack.
    4. BirthDate d1= New BirthDate (7,7,1970); D1 is an object reference, exists in the stack, the object (new BirthDate ()) exists in the heap, where D,m,y is stored in the stack for local variables, and their type is the underlying type, so their data is also stored in the stack. Day,month,year are member variables that are stored in the heap (new BirthDate ()). When the birthdate construction method finishes executing, the d,m,y disappears from the stack.
    5. After the main method executes, the date variable, TEST,D1 reference will disappear from the stack, new test (), new BirthDate () will wait for garbage collection.

Heap, stack, and Chang of Java Memory allocations (RPM)

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.