protected void finalize() Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. 回到B2,看上面的finalize解释,说是no more references ,那现在在B2中有一个指向A的引用a ,而且不为null,难道就意味着A对像不会被finalize ?
晕,把你的代码试了试,更离奇了。 import java.util.*; public class B1 {
public static void main(String[] args ) { Vector v = new Vector() ; //for(int i=0;i<1;i++) { A a = new A() ; v.add(a) ; //} v = null ; System.gc() ; } } 不拿注释,没输出,拿掉注释,输出一次A is killed!
试了: import java.util.* ;class A { protected void finalize(){ System.out.println("A is killed"); } } public class B2 { public static void main(String[] args ) { Vector v = new Vector() ; if(true) { A a = new A() ; v.add(a) ; a = null ; } v = null ; //System.gc() ; } } 什么都不输出
to shandd(猜不透): 如果不用System.gc()的话,应该也会有输出的,不过可能要等N久.
public class B {
public static void main(String[] args ) { for(boolean i=true;i;i=false){ Vector b = new Vector(); { A a1 = new A(); b.add(a1); //a1 = null; } //b = null; } System.gc(); } } 这里,采用for循环时,就算不显式b=null,a1= null ,也一样有输出,A is killed
从根出发(main方法)。凡是没有路径从根到达的都会被gc。所以
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. 回到B2,看上面的finalize解释,说是no more references ,那现在在B2中有一个指向A的引用a ,而且不为null,难道就意味着A对像不会被finalize ?
import java.util.*;
public class B1 {
public static void main(String[] args ) {
Vector v = new Vector() ;
//for(int i=0;i<1;i++) {
A a = new A() ;
v.add(a) ;
//}
v = null ;
System.gc() ;
}
}
不拿注释,没输出,拿掉注释,输出一次A is killed!
java采用有向图搜寻机制!
从根出发(main方法)。凡是没有路径从根到达的都会被gc。所以
这个搜索的机制会在某一个时刻触发(这个时刻用户无法控制),是不是?
import java.util.* ;class A {
protected void finalize(){
System.out.println("A is killed");
}
}
public class B2 { public static void main(String[] args ) {
Vector v = new Vector() ;
if(true) {
A a = new A() ;
v.add(a) ;
a = null ;
}
v = null ;
//System.gc() ;
}
}
什么都不输出
如果不用System.gc()的话,应该也会有输出的,不过可能要等N久.
public static void main(String[] args ) {
for(boolean i=true;i;i=false){
Vector b = new Vector();
{
A a1 = new A();
b.add(a1);
//a1 = null;
}
//b = null;
}
System.gc();
}
}
这里,采用for循环时,就算不显式b=null,a1= null ,也一样有输出,A is killed