1. Overview
In Java, memory is divided into two kinds, one is stack memory and the other is heap memory.
2. Heap Memory
1.什么是堆内存?
Heap memory is a type of Java memory that is used to store objects and arrays in Java, and when we new an object or create an array, it opens up a space in the heap memory for storage.
2.堆内存的特点是什么?
1th: The heap can actually be similar to the pipeline, or usually to queue to buy tickets in the same situation, so the characteristics of heap memory is: advanced first out, after the backward , that is, you first line up, good, you first buy tickets.
2nd: The heap can dynamically allocate memory size, and the lifetime does not have to tell the compiler beforehand because it allocates memory dynamically at runtime, but the disadvantage is that it is slower to allocate memory dynamically at run time.
3.new对象在堆中如何分配?
Managed by the Java Virtual machine's automatic garbage collector
3. Stack memory
1.什么是栈内存
Stack memory is another type of memory in Java, mainly used to execute programs, such as: basic types of variables and object reference variables
2.栈内存的特点
1th: Stack memory is like a mineral water bottle, like inside put things, then put into the bottom of the sink, so it is characterized by: advanced after, LIFO
2nd: The access speed is faster than the heap, second only to the register, the stack data can be shared, but the disadvantage is that the data size in the stack and the lifetime must be deterministic, lack of flexibility
3.栈内存分配机制
Stack memory can be called a primary cache and is automatically reclaimed by the garbage collector
4.数据共享
Example:
int a = 3;
int b = 3;
第一步处理:
1. The compiler processes int a = 3 first;
2. Create a reference to variable a
3. Find out if there is a value of 3 in the stack
4. Not found, store 3, a points to 3
第二步处理:
1. Handling b=3
2. Create a reference to variable B
3. Find, Direct assignment
第三步改变:
Next
A = 4;
Ibid method
The value of a is changed, and a point to the 4,b value is not changed.
PS: If it is two objects, then it is different, the object points to the same reference, one changes, the other changes
4. Stack and heap differences
The JVM is a stack-based virtual machine. The JVM allocates a stack for each newly created thread. In other words, for a Java program, it runs through the operation of the stack. The stack holds the state of the thread in frames. The JVM operates on the stack in only two ways: stack and stack operations in frames.
差异
1. Heap memory is used to store objects and arrays created by new.
2. Stack memory is used to store methods or local variables, etc.
3. Heap is FIFO, LIFO
4. Stack is LIFO, advanced after
相同
1. It's all part of Java memory.
2. The system will automatically recycle it, but for heap memory the developer will automatically recycle it
The difference between Java stacks