JVM (Java Virtual Machine) chia bộ nhớ thành 5 vùng chính:
5 Vùng nhớ JVM
| Vùng nhớ | Chức năng | Đặc điểm |
|---|---|---|
| Heap | Lưu trữ object (reference types) tại runtime | Chia sẻ cho tất cả thread. Có Garbage Collection. Chia: Young Gen (Eden, S0, S1), Old Gen. |
| Stack | Lưu biến local, tham số, kết quả trung gian, frame method | Mỗi thread có 1 stack riêng. Frame tạo khi gọi method, hủy khi return. LIFO. StackOverflowError nếu đệ quy sâu. |
| PC Registers (Program Counter) | Lưu địa chỉ instruction đang thực thi của thread | Mỗi thread 1 PC register. Non-native method: địa chỉ bytecode. Native method: undefined. |
| Method Area / Metaspace | Lưu class metadata, static variable, constant pool, method bytecode | Chia sẻ all thread. Java 8+: Metaspace (native memory), thay PermGen. OutOfMemoryError: Metaspace. |
| Native Method Stack | Lưu stack cho native method (JNI - C/C++) | Mỗi thread 1 native stack. Tương tự Java Stack nhưng cho native code. |
Sơ đồ minh họa
+-------------------------+ | JVM Process | +-------------------------+ | Heap (Shared) | <-- Objects, GC | Method Area/Metaspace | <-- Class metadata, static fields +-------------------------+ | Thread 1 | Thread 2 | Thread N | + Stack | + Stack | + Stack | + PC Register | + PC Register | + PC Register | + Native Stack | + Native Stack | + Native Stack +-------------------------+
Lưu ý quan trọng
- Heap là nơi GC hoạt động chính. Cấu hình:
-Xms(initial),-Xmx(max). - Stack size cấu hình:
-Xss(mặc định ~1MB). - Metaspace (Java 8+): Native memory, cấu hình
-XX:MaxMetaspaceSize. - Primitive local variable → Stack. Object reference → Stack, Object instance → Heap.