日期:2014-05-20  浏览次数:20720 次

哪位高人能给讲下堆内存和栈内存?
哪位高人能给讲下堆内存和栈内存,哪些是放在堆内存,哪些是在栈内存?谢谢!!  


------解决方案--------------------
需要动态分配内存的就是放在堆内存的,其他放在栈内存

比如int[] a;
a = new int [10];
首先在栈中分配一块内存放变量a,这时候a指向null, 然后用new 在堆栈中分配可以放10个整数的内存。并且把首地址送到变量a所在的栈内存空间里
------解决方案--------------------
这个东西就不用高手讲了。

在Java里讲栈几乎是没有啥用处的,因为new对象,都是在堆里的。
这和C++不一样。

你可以翻看以前很多贴字,都有这个话题的,不过最好是看我说的。。。
------解决方案--------------------
堆内存,
动态分配内存,new,或static!
栈内存
一些局部变量,如 public void n{ int x = 0; //作用域完了,x就完了}
------------------------
栈内存,一般都是作用域完了自动调用析构函数的(在java没有这个概念,但还是可以理解为他带有)
堆内存,这是和GC机制有关的!
------解决方案--------------------
其实没有什么堆内存和栈内存之分,JAVA只有一个堆内存
------解决方案--------------------
jdk文档解释:

Heap and Non-Heap Memory
The Java VM manages two kinds of memory: heap and non-heap memory, both of which are created when the Java VM starts.

Heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects.

Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous.

In addition to the method area, a Java VM may require memory for internal processing or optimization which also belongs to non-heap memory. For example, the Just-In-Time (JIT) compiler requires memory for storing the native machine code translated from the Java VM code for high performance