English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
销毁未引用对象的过程称为垃圾回收(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