Detailed analysis of heap and stack in Java

Source: Internet
Author: User

Detailed analysis of heap and stack in Java

To sum up the first sentence: When the Java language uses memory, the stack memory mainly stores the following content: Basic Data Types and object references, while the heap memory stores objects, stack memory is faster than heap memory. In summary, the object is referenced in the stack and the object is in the stack.


A conversation in Java's crazy handout serves as an opening remark.

One question: why are there stack memory and heap memory?

A: When a method is executed, each method will resume its own memory stack. The variables defined in this method will be put into the memory of this stack one by one. As the method execution ends, the memory stack of this method will also be destroyed naturally. Therefore, when an object is created in a method, the object will be saved to the runtime data area for reuse (because the object creation cost is usually large ), the runtime data zone is the heap memory. Objects in the heap memory will not be destroyed as the method ends. After the method ends, the object may be referenced by another reference, and the object will not be destroyed. The garbage collector of the system recycles an object only when it is not referenced.


First, highlight a self-made image:


Next we will parse the content of this figure.


Some of the basic types of variables defined in the function and the referenced variables of the object 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. When the scope of the variable is exceeded, java will automatically release the memory space allocated for the variable, and the memory space can be used for another use immediately.

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 automatic garbage collector. After an array or object is generated in the heap, you can define a special variable in the stack. The value of this variable is equal to the first address of the array or object in the heap memory, this special variable in the stack becomes an array or object reference variable. Later, you can use the reference variable in the stack memory in the program to access the array or object in the stack, the referenced variable is equivalent to an alias or code name for an array or object.

The referenced variable is a common variable. When defined, the memory is allocated in the stack. The referenced variable is released outside the scope of the program. Arrays and objects are allocated in the heap. Even if the program runs outside the code block where new statements are used to generate arrays and objects, the heap 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 again, but still occupy the memory. They are released by the garbage collector at an uncertain time. This is also the main reason why java accounts for memory usage. In fact, the variables in the stack point to the variables in the heap memory. This is the pointer in Java!


Comparison of memory allocation policies and heap and stack in java:

1. Memory Allocation Policy
According to the compilation principle, there are three policies for memory allocation during program running: static, stack, and heap ..
Static Storage Allocation refers to the ability to determine the storage space requirements of each data target at runtime during compilation. Therefore, a fixed memory space can be allocated to each data target during compilation. this allocation policy requires that the existence of a variable data structure (such as a variable array) or nested or recursive structure is not allowed in the program code, because they both cause compilation programs to fail to calculate accurate storage space requirements.

Languages that fully adopt static allocation policies must meet the following constraints:
1: recursive procedures are not allowed.
2: variable volume data is not allowed, that is, the length of the data object and its position in the memory must be known during compilation.
3: dynamically created data structures are not allowed because there is no storage allocation mechanism at runtime.
Stack-based storage allocation, also known as dynamic storage allocation, is implemented by a stack-like running stack. in contrast to static storage allocation, in stack-based storage solutions, the program's requirements for data areas are completely unknown during compilation and can only be known at runtime, however, when entering a program module during running, you must know the size of the Data zone required by the program module to allocate memory for it. like the stack we are familiar with in the data structure, stack-based storage allocation is distributed based on the principle of first-in-first-out.

The stack-based Dynamic Allocation Policy manages the memory as a stack at runtime. When a process/function is called, the space required for it is dynamically allocated and the stack top is pushed, the space it occupies is released.

Static storage allocation requires that the storage requirements of all variables be known during compilation, and stack-based storage allocation requires that all storage requirements be known at the entrance of the process, heap Storage allocation is specifically responsible for the memory allocation of data structures that cannot be determined at the module entrance during compilation or runtime, such as variable length strings and object instances. the heap consists of a large part of available blocks or idle blocks. The memory in the heap can be allocated and released in any order.

2 heap and stack comparison
The above knowledge is summarized from the compilation principle. In addition to static storage allocation, it seems very dull and hard to understand. The following describes static storage allocation, and compares stacks and stacks in a centralized manner.
Compared with the functions and functions of stacks, stacks are mainly used to store objects and stacks are mainly used to execute programs. this difference is mainly determined by the features of the stack and stack:
In programming, for example, in C/C ++, all method calls are performed through stacks, and all local variables and formal parameters are allocated memory space from stacks. In fact, there is no allocation, just use it from the top of the Stack, just like a conveyor belt in the factory (conveyor belt), Stack Pointer will automatically guide you to the place where you put things, all you have to do is put things down. when you exit the function, you can modify the stack pointer to destroy the stack content. this mode is the fastest, of course, used to run the program. it should be noted that, during the allocation, for example, when assigning a data zone to a program module to be called, the size of the Data zone should be known in advance, that is to say, although the allocation is performed while the program is running, the size of the allocation is fixed, and the "size" is determined during compilation, not at runtime.

Heap requests the operating system to allocate memory when the application is running. Because the memory allocated is managed by the operating system, it takes time to allocate and destroy the heap, therefore, the efficiency of using the heap is very low. however, the advantage of heap is that the compiler does not have to know how much storage space is allocated from the heap or how long the stored data will stay in the heap. Therefore, storing data in a heap gives you more flexibility. In fact, heap memory allocation is essential for object-oriented polymorphism, because the storage space required for Polymorphism variables can be determined only after the object is created at runtime. in C ++, when creating an object, you only need to use the new command to compile the relevant code. When the code is executed, data is automatically saved in the heap. of course, to achieve this flexibility, you must pay a certain price: It will take longer to allocate storage space in the heap! This is exactly the reason why we have just mentioned the low efficiency,

3. Stack and stack in JVM
JVM is a stack-based Virtual Machine. JVM allocates a stack for each newly created thread. That is to say, for a Java program, its operation is done through stack operations. The stack stores the thread status in frames. JVM only performs two types of operations on the stack: frame-based stack pressure and outbound stack operations.
We know that the method being executed by a thread is called the current method of this thread. We may not know that the frame used by the current method is called the current frame. When a thread activates a Java method, JVM will press a new frame into the thread's Java stack. This frame naturally becomes the current frame. during the execution of this method, this frame will be used to save parameters, local variables, intermediate calculation processes, and other data. this frame is similar to the activity record concept in the compilation principle.
From the perspective of Java's allocation mechanism, the Stack can be understood as follows: a Stack is a process or thread created by the operating system (a thread in an operating system that supports multithreading) the storage area created for this thread has the advanced and later features.


Each Java application corresponds to only one JVM instance, and each instance corresponds to only one heap. All the class instances or arrays created by the application during running are stored in this heap and shared by all the threads of the application. unlike C/C ++, heap memory allocation in Java is automatically initialized. In Java, the storage space of all objects is allocated in the heap, but the reference of this object is allocated in the stack. That is to say, the memory is allocated from both places when an object is created, the memory allocated in the heap actually creates this object, and the memory allocated in the stack is just a pointer (reference) pointing to this heap object.
JAVA stack differences:
Java divides memory into two types: stack memory and stack memory.
Variables of some basic types defined in the function and referenced variables of the object 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. When the scope of the variable is exceeded, java will automatically release the memory space allocated for the variable, and the memory space can be used for another use immediately.
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.
Specifically:
1. Both stack and heap are places where Java is used to store data in Ram. Unlike C ++, Java automatically manages stacks and stacks, and programmers cannot directly set stacks or stacks.
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.
2. The advantage of stack is that the access speed is faster than the heap speed, second only to the registers directly located in the CPU. However, the disadvantage is that the data size and lifetime in the stack must be fixed, and there is a lack of flexibility. In addition, stack data can be shared. For details, refer to the 3rd point. The advantage of heap is that the memory size can be dynamically allocated, and the lifetime does not have to be told to the compiler in advance. The Java garbage collector will automatically collect the data that is no longer used. However, the slow access speed is due to the need to dynamically allocate memory during runtime.
3. There are two data types in Java.
One is the basic type (primitive types). There are 4 types and 8 types, namely int, short, long, byte, float, double, boolean, char (note, there is no basic string type ). The definition of this type is defined in the form of int a = 3; long B = 255L;, which is called an automatic variable. It is worth noting that the automatic variable stores the literal value, not the instance of the class, that is, it is not the reference of the class, and there is no class here. For example, int a = 3; here, a is a reference pointing to the int type, pointing to the literal value of 3. Because of the size and lifetime of the nominal value data, we can see that (these nominal values are fixed in a program block, and the field value disappears after the program block exits). For the reason of speed, it exists in the stack.
In addition, the stack has a very important feature, that is, data in the stack can be shared. Suppose we define both:
Int a = 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 there is an address with the nominal value 3, not found, open up an address that stores the nominal value of 3, and then point a to the address of 3. Then process int B = 3. After the referenced variable of B is created, B is directed to the address of 3 because there is already 3 in the stack. In this way, both a and B point to 3 at the same time.
Note that the reference of this literal value is different from that of a Class Object. Assume that the references of two class objects point to one object at the same time. If an object's reference variable modifies the internal state of the object, the variable referenced by the other object immediately reflects this change. On the contrary, modifying the value by referencing the literal value does not cause another reference value pointing to the literal value to change. In the preceding example, after defining the values of a and B, make a = 4; then, B is not equal to 4 or 3. In the compiler, when a = 4; is encountered, it will re-search whether there is a 4-character nominal value in the stack, if not, re-open the address to store the 4 value; if yes, direct a to this address. Therefore, changing the value of a does not affect the value of B.
The other is the packaging class data, such as Integer, String, Double, and so on. All the data of these classes exist in the heap. Java uses the new () statement to display and tell the compiler that the class is dynamically created as needed during runtime, so it is flexible, however, the disadvantage is that it takes more time.

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.