1. 程式人生 > >Java中的堆記憶體和棧記憶體

Java中的堆記憶體和棧記憶體

Java中的堆記憶體和棧記憶體

本文主要討論作者對於Java記憶體中堆疊的理解.

Oralce官方對於棧(stack)的解釋:

Each Java Virtual Machine thread has a private Java Virtual Machine stack, created at the same time as the thread. A Java Virtual Machine stack stores frames (§2.6). A Java Virtual Machine stack is analogous to the stack of a conventional language such as C: it holds local variables and partial results, and plays a part in method invocation and return. Because the Java Virtual Machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated. The memory for a Java Virtual Machine stack does not need to be contiguous.

  • 棧中存放的是基本變數和物件的引用(或者叫引用變數)
  • 棧在方法物件和返回結果的時候起作用

對於堆(heap)的解釋:

Java Virtual Machine has a heap that is shared among all Java Virtual Machine threads. The heap is the run-time data area from which memory for all class instances and arrays is allocated.The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java Virtual Machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor's system requirements. The heap may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger heap becomes unnecessary. The memory for the heap does not need to be contiguous.

  • 堆中存放的是物件
  • 當沒有棧中的引用指向堆中的物件時,堆中的物件由自動垃圾回收器(garbage collector)負責回收,回收時間不確定

JVM是基於堆疊的虛擬機器.JVM為每個新建立的執行緒都分配一個堆疊.也就是說,對於一個Java程式來說,它的執行就是通過對堆疊的操作來完成的。堆疊以幀為單位儲存執行緒的狀態。JVM對堆疊只進行兩種操作:以幀為單位的壓棧和出棧操作。

當前方法使用的幀稱為當前幀。當執行緒啟用一個Java方法,JVM就會線上程的 Java堆疊裡新壓入一個幀。這個幀自然成為了當前幀.在此方法執行期間,這個幀將用來儲存引數,區域性變數,中間計算過程和其他資料.


[1]:Java中堆記憶體和棧記憶體詳解