如何在 Java 中使物件有資格進行 GC?
廢棄未引用物件的程序稱為垃圾回收 (GC)。一旦物件成為未引用物件,則視為該物件不再使用,因此 JVM 會自動廢棄該物件。
有各種方法可以讓物件有資格進行 GC。
透過將物件的引用置空
一旦建立物件的目的是到了,我們可以將所有可用的物件引用設為“null”。
示例
public class GCTest1 { public static void main(String [] args){ String str = "Welcome to TutorialsPoint"; // 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 TutorialsPoint"; 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
廣告