什么时候是垃圾收集的参考?

时间:2015-12-31 03:19:19

标签: java garbage-collection

class MyObj {
    public void print() {
        System.out.println("Hello!");
    }
    @Override
    protected void finalize() throws Throwable {
        System.out.println("MyObj Destroyed");
        super.finalize();
    }

    public static void main(String... args) {
        MyObj obj = new MyObj();
        obj.print();
        for (int i = 0; i < 10000000; i++) {
            byte[] b = new byte[100];
        }
        System.out.println("done");
    }
}
  

您好!
  MyObj被毁了   完成了

但是当我将main方法更改为此

public static void main(String... args) {
    MyObj obj = new MyObj();
    obj.print();
    for (int i = 0; i < 10000000; i++) { 
        byte[] b = new byte[100]; //just create objects to force garbage collector to run
    }
    obj.print(); //call print here
    System.out.println("done");
}
  

您好!
  您好!
  完成了

Java是否会在上次使用时自动设置对null的强引用?

1 个答案:

答案 0 :(得分:-1)

当对象无法再访问时,它有资格进行垃圾回收 仅仅因为一个对象有资格进行垃圾收集并不意味着它将被收集。