..
JVM Runtime Data Areas: Stack, Heap, Method Area
TOC
Overview
앞 글에서는 class 파일이 JVM 안에서 어떻게 사용되는지 봤다.
이번 글에서는 실행 중 JVM이 쓰는 메모리 영역을 짧게 나눠본다.
Stack
스택에는 메서드 호출마다 frame이 쌓인다. frame 안에는 지역 변수와 연산용 데이터가 들어간다.
public class StackDemo {
public static void main(String[] args) {
int count = 3;
print(count);
}
static void print(int value) {
System.out.println(value);
}
}
count와 value 같은 지역 변수는 스택 쪽에서 다룬다. 메서드가 끝나면 frame도 같이 사라진다.
Heap
객체는 heap에 할당된다.
public class HeapDemo {
public static void main(String[] args) {
Person person = new Person("kim");
}
}
class Person {
String name;
Person(String name) {
this.name = name;
}
}
person 변수는 참조고, 실제 Person 객체는 heap에 있다.
Method Area
클래스 정보와 static 관련 정보는 method area 쪽으로 생각하면 된다.
예를 들면 클래스 이름, 메서드 정보, static field 같은 것들이다. HotSpot에서는 이 영역의 구현이 Metaspace로 보인다.
정리
아주 단순하게 정리하면 이렇다.
- Stack: 메서드 호출과 지역 변수
- Heap: 객체
- Method Area: 클래스와 static 정보
Next Step
다음 글에서는 객체가 heap에 어떻게 올라가는지, 그리고 참조와 객체가 왜 다른지 본다.