The difference between heap and stack memory in JVM

  • 2020-06-12 09:16:44
  • OfStack

Java divides memory into two types, one called stack memory and the other called heap memory

Variables of basic types defined in functions and references to objects are allocated in the function's stack memory. When a variable is defined in a block of code, java allocates memory space in the stack for that variable. When the scope of the variable is exceeded, java automatically releases the memory space allocated for that variable, which can be immediately used for other purposes.

Heap memory is used to hold objects and arrays created by new. The memory allocated in the heap is managed by the java virtual machine automatic garbage collector. In the heap produced after an array or object, you can also define a special variable in the stack, value of this variable is equal to the array or object in the heap memory address, in this particular variable in the stack becomes an array or object reference variables, it can be used in the program after stack memory references in the variable to access in the heap array or object, or as an array or object reference variables 1 individual name, or symbol.

Reference variables are normal variables that are defined to allocate memory on the stack and are released when the program runs out of scope. And allocated in the heap array & object itself, even if the program runs to use new generate array and object code block in the locality of the statements, arrays, and the object itself retained heap memory will not be released, arrays and objects in the absence of reference variable pointing to it, to become garbage, can no longer be used, but still account for the memory, in the following an uncertain time released by the garbage collector. This is also the main reason why java takes up so much memory. In fact, stack variables point to heap memory variables, which are Pointers in Java!

Comparison of memory allocation policies and heap and stack in java

Memory allocation strategy

According to compilation principles, there are three strategies for allocating memory while a program is running: static, stack, and heap.

Static storage allocation is to point to each data can be determined at compile time goal at run time of storage space requirements, and therefore can be assigned to them at compile time fixed memory space. In this allocation policy requires code does not allow to have the presence of variable data structures (such as variable array), there are not allowed to nested or recursive structure, because they can all result in a compiler can't calculate accurate storage needs.

Stacked storage allocation can also be called dynamic storage allocation, is the one similar to the operation of the stack stack. And static storage allocation, by contrast, in stacked storage scheme, process the demand of data is completely unknown at compile time, only to run time to know, but the rules into a program module in the running, must know the program module for data area size to allocate memory for it. And our stack in data structure known as sample 1, stacked storage allocation according to the principle of advanced out after.

Static storage allocation request to know at compile time the storage requirements of all variables, stacked storage allocation requirements at the entrance of the process must know all the storage requirements, and pile type storage allocation is responsible for at the entrance to compile or runtime modules can determine the data structure of the memory allocation of storage requirements, such as a variable length string and the object instance. Pile is composed of large block or available free block, can be in any order in the heap memory allocation and release.

Comparison of heap and stack

The above definitions are summarized in the textbook of compilation principles, which are dull and hard to understand except for static storage allocation. Let's leave the static storage allocation aside and compare the heap and stack in a centralized way:

In terms of the functions and functions of the heap and stack, the heap is mainly used to store objects, and the stack is mainly used to execute programs.

In programming, such as C/C++, all method calls are made through the stack, and all local variables, formal parameters are allocated from the stack. It's not really allocation, it's just going up the top of the stack, it's like a conveyor belt in a factory, conveyor belt,Stack Pointer will show you where to put things, all you have to do is put things down. Modify the stack pointer to the contents of the stack is destroyed. The fastest mode, of course, be used to run the program. It is important to note that at the time of distribution, such as one is going to call the program module of distribution data area should know in advance the size of the data area, and as though distribution was conducted in the program is running, but the size of distribution and how much is certain, constant, and the "how many" size is determined at compile time, not at run time.

Heap is the application at run time request the operating system memory allocated to himself, because from the operating system management of the memory allocation, so take time when allocating and destroyed, so the efficiency of the reactor is very low. But the strength of pile is that the compiler doesn't have to know how much storage space to be allocated from the heap, also don't have to know the data stored in the heap stay much longer, therefore, preserve data will get greater flexibility in the heap. In fact, for object-oriented polymorphism, heap memory allocation is essential, as the storage space required for polymorphic variables can only be determined after the object is created at runtime. In C++, when an object is required to be created, only the code associated with the new command can be compiled. When this code is executed, data is automatically saved in the heap. Of course, there is a price to pay for this flexibility: it takes longer to allocate storage space in the heap! This is also the reason for the inefficiency we have just mentioned. It seems that Comrade Lenin said well that human strengths are often also human weaknesses, and human weaknesses are often also human strengths.

Heap and stack in JVM

JVM is a stack-based virtual machine.JVM allocates one stack for each newly created thread. That is, for an Java program, it runs by manipulating the stack. The stack holds the state of the thread in frames. JVM does only two things with stacks: push and push in frames.

We know that a thread is executing a method called the thread's current method. When a thread activates an Java method,JVM presses 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 hold parameters, local variables, intermediate calculations, and other data. This frame here is similar to the concept of active recording in compilation principle.

From the perspective of Java's allocation mechanism, the stack (Stack) is the storage area established by the operating system for a process or by a thread (in the case of a multithreaded operating system), which has advanced features.

For every Java application, there are only 1 instance of JVM and 1 instance of heap. All class instances or arrays created by the application at run time are placed in the heap and Shared by all threads of the application. Unlike C/C++, allocating heap memory in Java is automatically initialized. Java of all objects from the storage space is allocated in the heap, but the object reference is allocated in the stack, that is to say, in establishing a object from two places are allocated memory, the memory allocated in the heap of actual build this object, and the memory allocated in the stack is a pointer to the object heap (reference).

The heap and stack in Java

Java divides memory into two types: stack memory and heap memory.

Variables of basic types defined in functions and references to objects are allocated in the function's stack memory.

When a variable is defined in a block of code, Java allocates memory for this variable in the stack. When the scope of the variable is exceeded, Java automatically releases the memory allocated for this variable, which can be immediately used for other purposes.

Heap memory is used to hold objects and arrays created by new.

The memory allocated in the heap is managed by the Java virtual machine's automatic garbage collector.

Once an array or object is created in the heap, you can define a special variable on the stack that is equal to the first address of the array or object in the heap memory, and the variable on the stack becomes the reference variable of the array or object.

A reference variable is the equivalent of a name for an array or object that can be accessed in a program using a reference variable from the stack.

To be specific:

The stack and heap are both places where Java USES to store data in Ram. Unlike C++, Java manages stacks and heaps automatically, and programmers cannot directly set stacks or heaps.

The heap of Java is a runtime data area from which the class (object) allocates space. These objects are created using the new, newarray, anewarray, and multianewarray directives and do not require program code to be explicitly released. The heap is taken care of by garbage collection. The advantage of the heap is that the memory size can be allocated dynamically, and the lifetime of the heap does not have to be told to the compiler in advance, because it is allocated dynamically at run time, and Java's garbage collector automatically picks up data that is no longer used. However, the disadvantage is that due to the dynamic allocation of memory at runtime, the access speed is slow.

The stack has the advantage that access is faster than the heap, second only to registers, and stack data can be Shared. The disadvantage is that the size and lifetime of the data in the stack must be determined and inflexible. The stack contains 1 variable of basic type (,int, short, long, byte, float, double, boolean, char) and object handle.

The stack has one very important distinction, that is, the data that exists in the stack can be Shared. Suppose we simultaneously define:


int a = 3; 
int b = 3; 

The compiler processes int a = 3; First it creates a reference to a on the stack, then looks for a value of 3 on the stack, if it doesn't find it, puts 3 in, and points a to 3. Next, int b = 3; After the reference variable for b is created, b is pointed directly to 3 because the value 3 is already on the stack. Thus, a and b both point to 3 at the same time. So if I set a=4; Then the compiler will re-search for the value of 4 in the stack, if not, it will store the 4 in, and let a point to 4; If it already exists, point a directly to the address. Therefore, the change of a value will not affect the value of b. Note that this sharing of data is different from the sharing of two object references pointing to one object at the same time, because a changes in this case do not affect b, it is done by the compiler, and it saves space. An object reference variable modifies the internal state of that object, affecting another object reference variable


Related articles: