[Java] Stack vs Heap 메모리

박현아·2025년 5월 17일
0

Java

목록 보기
1/1
post-thumbnail

🧠 Java에서 Stack과 Heap의 차이

📌 Stack 영역

  • 메서드 호출 시 생성되는 프레임과 지역 변수가 저장되는 공간입니다.
  • 후입선출 (LIFO, Last In First Out) 구조로 동작합니다.
  • 메서드가 호출되면 메모리가 자동으로 할당되고, 메서드가 끝나면 자동으로 해제됩니다.
  • 속도가 빠르며, 각 스레드마다 독립적인 스택을 가집니다 → 스레드 안전(Thread-safe)
void example() {
    int x = 10; // x는 Stack에 저장됨
}

📌 Heap 영역

  • new 키워드를 통해 생성된 객체가 저장되는 공간입니다.
  • 메모리는 동적으로 할당되며, 가비지 컬렉터(Garbage Collector)가 관리합니다.
  • Stack보다 속도가 느리지만, 객체는 프로그램 전반에서 공유될 수 있습니다.
  • 여러 스레드가 접근 가능하기 때문에 동기화(synchronization)가 필요할 수 있습니다.
Person p = new Person(); // p는 Stack에, 실제 Person 객체는 Heap에 저장됨

🔍 요약 표:

🧠 Stack vs Heap in Java

📌 Stack

  • The stack is a region of memory that stores method call frames and local variables.
  • It follows the Last In, First Out (LIFO) principle.
  • Memory is automatically allocated and deallocated when methods are called and return.
  • It is faster than the heap.
  • Each thread has its own stack, so it's thread-safe.
  • Example:
    When you declare a local variable like int x = 10; inside a method, it's stored in the stack.

📌 Heap

  • The heap is a region of memory used for dynamic memory allocation.
  • Objects created using new are stored in the heap.
  • Memory in the heap is managed by the Garbage Collector.
  • It is slower compared to the stack.
  • The heap is shared among all threads, so you need to handle synchronization for thread safety.
  • Example:
    When you write Person p = new Person();, the Person object is created in the heap, while the reference p is stored in the stack.

🔍 Summary Table:

🧠 Pile (Stack) vs Tas (Heap) en Java

📌 Pile (Stack)

  • La pile est une zone mémoire qui stocke les frames d’appel de méthode et les variables locales.
  • Elle suit le principe dernier entré, premier sorti (LIFO).
  • La mémoire y est allouée et libérée automatiquement à chaque appel et retour de méthode.
  • Elle est plus rapide que le tas.
  • Chaque thread dispose de sa propre pile, ce qui la rend thread-safe.
  • Exemple :
    Lorsque vous déclarez une variable locale comme int x = 10; dans une méthode, x est stockée dans la pile.

📌 Tas (Heap)

  • Le tas est une zone mémoire utilisée pour l’allocation dynamique.
  • Les objets créés avec new sont stockés dans le tas.
  • La gestion de la mémoire est assurée par le ramasse-miettes (Garbage Collector).
  • Il est plus lent que la pile.
  • Le tas est partagé entre tous les threads, donc synchronisation nécessaire pour la sécurité des accès concurrents.
  • Exemple :
    Avec Person p = new Person();, l’objet Person est créé dans le tas, tandis que la référence p est stockée dans la pile.

🔍 Tableau récapitulatif

0개의 댓글