Learning about heap and stack in Java

1 Overview

In Java, memory is divided into two types, one is stack memory and the other is heap memory .

When the program is running, JAVA divides 5 pieces of space in the memory for data storage. They are:

  1. register.
  2. native method area
  3. method area.
  4. stack.
  5. heap.

1.1 heap

It can be understood as a restaurant, which has 200 tables, that is, it can accommodate up to 200 tables of guests at the same time, and arrange some tables for them when a group of guests come. If there are too many guests on a certain day, more than 200 tables, Then no more guests can be received.
Of course, the guests who come in for dinner cannot be at the same time. Some are early and some are late. The boss will arrange for the guests who have eaten first, to check out and leave, and then the vacated table can receive new guests.
Here, the heap is the restaurant, and the maximum capacity of 200 tables is the size of the heap memory. The boss is equivalent to GC (garbage collection). Space.

1.2 stack

Then compare the stack to an abandoned well. This well has run out of water after many years of use. The owner now uses it as a place to store self-brewed wine. When storing wine, he hooks the wine jar with a rope and lowers it slowly. The jars are piled up one by one, and when the wine is taken, the top jar is taken first.

2. Heap memory

2.1 What is heap memory?

Heap memory is a kind of Java memory. Its function is to store objects and arrays in Java . When we create a new object or create an array, we will open up a space in the heap memory for it. Use in storage.

2.2 What are the characteristics of heap memory?

The first point: the heap can actually be regarded as a pipeline , or the situation of queuing up to buy tickets is similar, so the characteristics of the heap memory are: first in , first out, last in, last out, that is, you queue first, okay, You buy the ticket first.

The second point: the heap can dynamically allocate memory size , and the lifetime does not need to tell the compiler in advance, because it dynamically allocates memory at runtime, but the disadvantage is that due to the dynamic allocation of memory at runtime, the access speed is slow .

2.3 How are new objects allocated in the heap?

Managed by the Java Virtual Machine's automatic garbage collector

3. Stack memory

3.1 What is stack memory?

Stack memory is another kind of memory in Java, which is mainly used to execute programs , such as: variables of basic types and reference variables of objects

3.2 Characteristics of stack memory

The first point: The stack memory is like a mineral water bottle. If you put something in it, the first one will sink to the bottom, so its characteristics are: first in first out, last in first out

The second point: the access speed is faster than the heap, second only to the register , and the stack data can be shared, but the disadvantage is that the data size and lifetime in the stack must be determined, which lacks flexibility

3.3 Memory allocation mechanism of stack memory

Stack memory can be called level 1 cache, which is automatically reclaimed by the garbage collector

3.4 Data Sharing

example:

int a = 3;
int b = 3;
the first step of processing:
1. The compiler first processes int a = 3;
2. Create a reference to the variable a
3. Check whether there is a value of 3 in the stack
4. If not found, it will be 3 is stored, a points to 3
The second step of processing:
1. Process b=3
2. Create a reference to the variable b
3. Find it and assign it directly
The third step changes:
Next
a = 4; the value of a changes
in the same method as above , and a points to
4. The value of b will not change.
If there are two objects, it will be different. The objects point to the same reference. If one changes, the other will also change.

4. The difference between stack and heap

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 completed through the operation of the stack. The stack saves the state of the thread in units of frames. The JVM only performs two operations on the stack: push and pop operations in units of frames .

4.1 Differences

1. Heap memory is used to store objects and arrays created by new.
2. The stack memory is used to store methods or local variables, etc.
3. The heap is first-in, first-out, last-in-last-out
4. The stack is first-in-last-out, last-in-first-out

4.2 same

1. It is a kind of Java memory
2. The system will automatically recycle it, but for heap memory, developers will automatically recycle it

5. Interview question: The difference between java heap and stack

The Java stack is associated with each thread. When the JVM creates each thread, it will allocate a certain amount of stack space to the thread, mainly storing local variables during thread execution, method return values, and basic types of variables (, int , short, long, byte, float, double, boolean, char) and the context of the method call. The stack space is released with the termination of the thread. The advantage of the stack is that the access speed is faster than the heap, and the stack data can be shared. But the disadvantage is that the size and lifetime of the data stored in the stack must be determined, which lacks flexibility. The stack has a very important particularity , that is, the data stored in the stack can be shared.

The heap in Java is a memory area shared by all threads. The heap is used to save various JAVA objects, such as arrays, thread objects, etc. The java heap is a runtime data area, and the class (object allocates space from it. These objects Created by instructions such as new, newarray, anewarray, and multianewarray, they do not require program code to be explicitly released. The heap is responsible for garbage collection. The advantage of the heap is that it can dynamically allocate memory size, and the lifetime does not need to be told to compile in advance. Because it dynamically allocates memory at runtime, Java's garbage collector will automatically take away these no longer used data. But the disadvantage is that due to the dynamic allocation of memory at runtime, the access speed is slow.

How to apply

  • Stack: automatically allocated by the system . For example, when declaring a local variable int b of a function, the system automatically creates space for b in the stack.
  • Heap: The programmer needs to apply for it by himself and specify the size . In C, use the malloc function; in C++, use the new operator.

System response after application

  • Stack: As long as the remaining space of the stack is greater than the requested space, the system will provide memory for the program, otherwise an exception will be reported indicating stack overflow.
  • Heap: The operating system has a linked list that records the memory address of the space. When the system receives an application from a program, it will traverse the linked list to find the first heap node whose space is larger than the requested space, and then delete the node from the linked list of free memory nodes. And allocate the space of this node to the program. For most operating systems, the size of this allocation will be recorded at the first address in this memory space, so that the delete statement in the code can correctly release this memory space. In addition, since the size of the found pair node is not necessarily exactly equal to the requested size, the system will automatically put the redundant part back into the linked list .

Application Size Limits

Stack: Under Windows, the stack is a data structure that expands to low addresses and is a continuous memory area . The station address and the size of the stack are predetermined by the system. If the requested memory space exceeds the remaining space of the stack, a stack overflow will be prompted .
Heap: The heap is a memory structure that expands to high addresses and is a discontinuous memory area. The system uses a linked list to store free memory addresses, which are discontinuous .

Comparison of Application Efficiency

  • Stack: automatically allocated by the system, faster. But programmers have no control.
  • Heap: The memory allocated by new is generally slow and prone to memory fragmentation, but it is convenient to use.

**Expansion:** In the Windows operating system, the best way to use VirtualAlloc to allocate memory. It is not on the heap, not on the stack, but reserves a block of memory in the memory space. Although it is inconvenient to use, it is fast and flexible.

Storage contents of the heap and stack

  • Stack: When a function is called, the first thing that is pushed into the stack is the address of the next instruction in the main function (the next executable statement of the function call), and then the parameters of the function. In the C compiler, the parameters are pushed on the stack from right to left, and then the local variables of the function. Static variables are not pushed onto the stack.
  • Heap: Generally, one byte is used to store the size of the heap at the head of the heap. The specific content of the heap is arranged by the programmer.

The heap and stack in terms of data structure are different from those described above. The heap here refers to a data structure of the priority queue , the first element has the highest priority; the stack is actually a mathematical or data structure that satisfies the nature of first-in-last-out .

Reference article (invasion and deletion):
The difference between the Java heap and the stack, and
a thorough understanding of the heap and stack in Java in one minute

Guess you like

Origin blog.csdn.net/mfysss/article/details/129727160
Recommended