English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java에서 객체가 GC 조건을 만족시키는 방법이 몇 가지인가요?

미참조된 객체를 소멸하는 과정을garbage collection(GC)。객체를 참조에서 해제한 후, 사용되지 않은 객체로 간주합니다. 따라서JVM이 자동으로 해당 객체를 소멸합니다.

객체가 GC 조건을 만족할 수 있는 여러 가지 방법이 있습니다.

객체에 대한 참조를 취소함으로써

대상 객체를 생성한 목적에 도달한 후, 모든 사용 가능한 객체 참조를 " null ”。

예제

public class GCTest1 {
   public static void main(String [] args){
      String str = "Welcome to w3codebox"; // String object referenced by variable str and it is       not eligible for GC yet.
      str = null; // String object referenced by variable str is eligible for GC.
      System.out.println("str eligible for GC: " + str);
   }
}

출력 결과

str eligible for GC: null


참조 변수를 다른 객체로 재할당함으로써

대상 변수가 다른 객체를 참조하도록 할 수 있습니다. 참조 변수를 객체와 결합해제하고 다른 객체로 설정하면 이전에 참조했던 객체를 GC가 사용할 수 있습니다.

예제

public class GCTest2 {
   public static void main(String [] args){
      String str1 = "Welcome to w3codebox";
      String str2 = "Welcome to Tutorix"; // String object referenced by variable str1 and str2 and         is not eligible for GC yet.
      str1 = str2; // String object referenced by variable str1 is eligible for GC.
      System.out.println("str1: " + str1);
   }
}

출력 결과

str1: Welcome to Tutorix
추천 강의