JVM Stack Area จุดสำคัญ
- สร้าง stack แยกต่างหากสำหรับแต่ละ thread ตอนสร้าง thread
- JVM ทำได้แค่ 2 ออปเตอร์ชัน: push (เพิ่ม) และ pop (ลบ)
- Stack ของ thread ที่ทำงานอยู่ เรียกว่า Runtime Stack
- ทุกการเรียกเมธอด การคำนวณระหว่างทาง ตัวแปรท้องถิ่น พารามิเตอร์ → เก็บเป็น stack frame
- เมธอดจบ → stack frame นั้นถูกลบ (pop)
- ทุกเมธอดจบ → stack ว่าง → ถูกลบจากหน่วยความจำ
- ก่อนจบ thread → JVM ทำลาย stack ของ thread นั้น
- Stack เป็น thread-local → thread-safe โดยธรรมชาติ
- ข้อมูลใน stack frame เรียกว่า Activation Record
- ไม่จำเป็นว่า stack ต้องอยู่ใน memory contiguous
โครงสร้าง Stack Frame (Activation Record)
ประกอบด้วย 3 ส่วนหลัก:
1. Local Variable Array
- เก็บพารามิเตอร์และตัวแปรท้องถิ่น (local variables)
- จัดเก็บเป็น array เรียงลำดับ index 0, 1, 2...
- index 0 = this reference (instance method) หรือว่าง (static method)
- ขนาดกำหนดตอน compile-time จาก bytecode
2. Operand Stack
- ทำงานเป็น workspace สำหรับ JVM
- เก็บผลลัพธ์ระหว่างคำนวณ (intermediate results)
- เข้าถึงแบบ push/pop (stack-based computation)
- เช่น
iaddpop 2 ค่า บวกกัน push ผลลัพธ์กลับเข้าไป
3. Frame Data
- Constant pool reference (สำหรับ resolve constants)
- Method return address (กลับไปที่ไหนหลังจบเมธอด)
- Exception Table Reference - อ้างอิงตาราง exception handler (catch blocks)
- ข้อมูลสำหรับการ debug (line number table, local variable table)
ตัวอย่างการทำงาน
public class Demo {
public static void main(String[] args) {
int a = 10; // Local variable array: a=10
int b = add(a, 20); // Call add -> push new frame
System.out.println(b);
}
static int add(int x, int y) {
int sum = x + y; // Operand stack: push x, push y, iadd, store sum
return sum; // Return -> pop frame, push result to caller's operand stack
}
}
Stack Frame Evolution
- main เริ่ม: Frame main (local: args, a, b | operand: empty)
- call add(10, 20): Push Frame add (local: x=10, y=20 | operand: empty)
- ใน add: operand push 10, push 20 → iadd → push 30 → store sum=30
- return: Pop Frame add, push 30 กลับไป operand stack ของ main
- main ต่อ: store b=30, call println...
ข้อแตกต่าง Stack vs Heap
| คุณสมบัติ | Stack | Heap |
|---|---|---|
| Scope | Thread-local | Shared (all threads) |
| Lifetime | Method call scope | Object lifetime (GC managed) |
| Speed | เร็วมาก (pointer bump) | ช้ากว่า (allocation + GC) |
| Size | คงที่/จำกัด (-Xss) | ใหญ่ กว้าง (-Xmx) |
| เก็บอะไร | Primitives, references, frames | Objects, arrays |