有多少种方法可以让 Java 中的对象符合 GC 的要求?

javaobject oriented programmingprogramming

销毁未引用对象的过程称为垃圾收集 (GC)。一旦对象不再被引用,它就被视为未使用的对象,因此 JVM  会自动销毁该对象。

有多种方法可以让对象符合 GC 的要求。

通过使对对象的引用无效

一旦创建对象的目的已实现,我们可以将所有可用的对象引用设置为"null"。

示例

public class GCTest1 {
   public static void main(String [] args){
      String str = "Welcome to TutorialsPoint"; // 字符串对象由变量 str 引用,并且它尚未符合 GC 条件。
      str = null; // 字符串对象由变量 str 引用,符合 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 TutorialsPoint";
      String str2 = "Welcome to Tutorix"; // 变量 str1 和 str2 以及         引用的字符串对象尚不符合 GC 资格。
      str1 = str2; // 变量 str1 引用的字符串对象符合 GC 资格。
      System.out.println("str1: " + str1);
   }
}

输出

str1: Welcome to Tutorix

相关文章