상세 컨텐츠

본문 제목

JVM 메모리 관리

Java

by Wanderer Kim 2023. 5. 29. 20:29

본문

728x90

JVM 기반 애플리케이션을 운영하다보면 성능 이슈 때문에 JVM 메모리 관리를 알고 있어야 하는 경우가 많은데 이번 블로그에서는 JVM은 어떻게 메모리 관리를 하는지 알아보겠다.

 

Java Memory Area

Java의 메모리 모델은 크게 아래의 세가지로 나누어 진다.

  • Heap : Heap에는 객체와 인스턴스 변수등이 저장되는 공간이다.
  • Stack : method 실행을 관리하기 위해 있는 공간이다. 이 공간에는 method call frame과 local variable등이 저장된다.ㅏ
  • Metaspace : class 정보와 static 데이터등이 저장되는 공간이다.

Stack

stack은 method execution을 관리하는 공간이다. 이 공간에서는 method call frame, local variable, heap에 있는 object 참조 정보 등이 관리된다. stack은 thread별로 각각 가지고 있고, thread간 독립성을 보장한다.

Stack의 특징

  • Local Variables and References : stack에는 local variable이 저장된다.
public class Main {
    public void methodA() {
        int x = 5; // Stored in the stack
        Car myCar = new Car(); // Reference is in the stack; object is in the heap
    }
}

 

  • LIFO : stack은 LIFO에 따라 데이터를 적재 및 해체한다.
    • StackOverFlowError: 만약 stack의 공간이 없으면 StackOverFlowError가 발생한다.
    • Performance : stack 메로릭는 간단한 구조와 garbage collection이 필요 없이 때문에 stack 메로리 공간 접근은 heap 메모리 접근보다 빠르다.

Heap

Heap은 동적 할당이 이루어지는 메모리 공간이다. 주로 runtime에 생성되는 객체들을 저장하는 역할을 한다.

그리고 객체들이 더 이상 참조되지 않으면 garbage collection에 의해 자동으로 정리된다.

Heap의 특징

  • instance variable과 Object 할당 : "new" 키워드를 통해서 새로운 object를 만들면 해당 object는 heap 공간에 저장된다.
class Car {
    public String color;
}

public class Main {
    public static void main(String[] args) {
        new Car();         // Anew Car object Allocated on the heap, but its reference is not preserved! (not accesible/referenced) Garbage collection eligible): 
        Car myCar;         // Reference type Varaiable (allocated on the stack) (pointing to null)
        myCar = new Car(); // New Car object Allocated on the heap and its reference stored on myCar on the stack.
        mycar.color = "Black"; // New String object allocated in heap and its reference is stored in instance reference variabl color of the object
    }
}

  • Garbage Collection : Heap 공간에 저장된 Object들은 Garbage Collection의 대상이된다.
  • Access : Heap의 경우 모든 thread에 공유된다.

Metaspace(Method Area)

metaspace에는 class의 메타데이터 즉, field 정보, method 이름과 constants등이 저장된다. 

metaspace 특징

  • class metadata : class의 field 정보, method 정보등이 저장된다.
  • constant pool : method 이름과 lietral과 같은 constant 값이 저장된다.
  • static variable : class에 있는 static variable과 constant data 등이 저장된다.

 

Comparing Heap, Stack, and Metaspace

 

결론

Heap, Stack, metaspace에 특징과 garbage collection이 해당 메모리 영역들에 어떻게 작동하는지 이해하는 것은 효율적인 Java apllcation을 만드는데 필수적이다. 그러므로 해당 블로그를 통해 JVM에서 메모리가 어떻게 관리되는지 잘 이해하자.

반응형

'Java' 카테고리의 다른 글

Object class  (0) 2025.02.16
Concurrent Random Number  (0) 2024.09.24
ThreadLocal  (1) 2024.02.28
Stream API 개요  (0) 2023.05.05
CompletableFuture get()과 join()의 차이점  (0) 2023.05.02

관련글 더보기