경계의 경계

자바의 Garbage Collection 본문

Java

자바의 Garbage Collection

gigyesik 2024. 3. 2. 04:31

Garbage Collection 이란 무엇인가

자바 프로그램이 JVM 에서 실행되면, 객체들은 힙 영역에 저장되고, 메모리 공간을 차지한다.

Garbage Collection 이란 자바 프로그램 내에서 메모리를 관리하기 위해 객체 할당을 자동으로 해제하는 과정을 말한다.

객체 할당 해제 방법들

할당된 객체를 null 로 만들기

GarbageCollectionTest g1 = new GarbageCollectionTest();
g1 =  null;
System.out.println(g1); // null

객체의 할당을 다른 객체로 바꾸기

GarbageCollectionTest g2 = new GarbageCollectionTest();
GarbageCollectionTest g3 = new GarbageCollectionTest();
System.out.println(g2);
System.out.println(g3);
g2 = g3;
System.out.println(g2);

익명 객체 이용하기

System.out.println(new GarbageCollectionTest());

Garbage Collection 에 사용되는 메서드들

  • Object.finalize()
  • System.gc()
  • 시스템 영역 스레드에서 호출되므로 구현시 신경써야 한다
g3.finalize();

System.gc();

References

'Java' 카테고리의 다른 글

자바의 쓰레드 관리  (0) 2024.03.02
자바의 JVM  (0) 2024.03.01
자바의 Stream  (1) 2024.02.29
자바의 제네릭 (Generic)  (1) 2024.02.28
자바의 네트워킹과 소켓 통신  (1) 2024.02.27