(Transfer) The difference between Java heap and stack

(Original reprinted from: http://blog.csdn.net/u011546655/article/details/52170470 )

 

1 Overview

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

2. Heap memory

1.什么是堆内存?

Heap memory is a type 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. for storage.

2.堆内存的特点是什么?

The first point: the heap can be regarded as a pipeline in a similar way, 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 and last out, that is, you queue first, okay, You buy tickets first.

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

3.new对象在堆中如何分配?

Managed by the automatic garbage collector of the Java virtual machine

3. Stack memory

1.什么是栈内存

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

2.栈内存的特点

The first point: the stack memory is like a mineral water bottle. If you put something in it, then the first one will sink to the bottom, so its characteristics are: first in, last 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 size and lifetime of the data stored in the stack must be determined, which lacks flexibility

3.栈内存分配机制

The stack memory can be called the first level cache, which is automatically reclaimed by the garbage collector

4.数据共享

Example: 
int a = 3; 
int b = 3;

第一步处理:

1. The compiler first processes int a = 3; 
2. Creates a reference to variable a 
3. Checks the stack to see if there is a value of 3 
4. If not found, store 3, and a points to 3

第二步处理:

1. Process b=3 
2. Create a reference to variable b 
3. Find and assign directly

第三步改变:

接下来 
a = 4; 
同上方法 
a的值改变,a指向4,b的值是不会发生改变的

PS:如果是两个对象的话,那就不一样了,对象指向的是同一个引用,一个发生改变,另一个也会发生改变

4、栈和堆的区别

JVM是基于堆栈的虚拟机.JVM为每个新创建的线程都分配一个堆栈.也就是说,对于一个Java程序来说,它的运行就是通过对堆栈的操作来完成的。堆栈以帧为单位保存线程的状态。JVM对堆栈只进行两种操作:以帧为单位的压栈和出栈操作。

差异

1.堆内存用来存放由new创建的对象和数组。 
2.栈内存用来存放方法或者局部变量等 
3.堆是先进先出,后进后出 
4.栈是后进先出,先进后出

相同

1.都是属于Java内存的一种 
2.系统都会自动去回收它,但是对于堆内存一般开发人员会自动回收它

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326638122&siteId=291194637
Recommended