java内存回收,目前普遍采用的是可达性算法,而非计数算法,即只有当对象对于GC root,也就是对象树可达时,即存在你甭到达该对象的引用路径存在时,该对象才不会被回收,也就是说,只有存在于GC root上的对象引用了你的对象时,你的对象才不会被归类为垃圾对象,当你的对象引用了GC root上的对象,而GC root上的对象未引用你的对象时,这种情况下,GC root不存在能到达你对象的路径,所以你的对象依旧会被回收。
证明:
import java.util.ArrayList; import java.util.Scanner; public class Test { static Student student; public static void main(String[] ags) { while (true) { Scanner sc = new Scanner(System.in); String name = sc.nextLine(); //读取字符串型输入 switch (name) { case "A": student = new Student(); break; case "B": student.closeZ(); break; case "C": student.clean(); break; case "D": student.create(); break; case "E": student.close(); break; } } } } public class Student { private StudentModel studentModel; public Student() { studentModel = new StudentModel(this); } public void clean( ) { studentModel.clean(); } public void create( ) { studentModel.create(); } public void close( ) { studentModel.close(); } public void closeZ( ) { studentModel = null; } } public class StudentModel { Object object; private byte[] a ; public StudentModel(Object object){ this.object = object ; a = new byte[1024*1024*1024]; } public void clean( ) { a = null; } public void create( ) { a = new byte[1024*1024*1024]; } public void close( ) { object = null; } }当程序运行时:
当在控制台输入A时:
当在控制台输入B并启动GC后时: