public class UAA { public static void main(String[] args) { UAA a = new UAA(); a = null; System.gc(); while(true); } public void finalize(){ System.out.println("finalize!!!! AAAAA"); } } 为什么这里gc()能马上调用finalize()
楼主可以试试这个程序import java.lang.ref.*;public class Test { public static void main(String[] args) { String a = new String("此对象还未被回收!"); WeakReference b = new WeakReference(a); System.out.println(b.get()); //移除强引用 a = null; //呼叫gc System.gc(); //对象不是应该被finalize? if(b.get() == null) System.out.println("对象被回收了!"); else System.out.println(b.get()); System.exit(0); } }
虽然Sun的文档都声明不要期望GC能立刻回收垃圾对象,但实际上GC回收对象的速度还是很快的。 下面的程序可以证明这一点,每次sleep之前的GC调用都导致对象立即被回收。public class GCTest { public static void main(String[] args) throws InterruptedException { Obj obj1 = new Obj(); Obj obj2 = new Obj(); System.out.println("begin."); Thread.sleep(2000); obj1 = null; System.gc(); Thread.sleep(2000); obj2 = null; System.gc(); Thread.sleep(2000); System.out.println("end."); } }class Obj { public void finalize() { System.out.println(this + " is finalized."); } }尽管如此,对GC抱不信任态度还是明智的,特别地,不要重要的程序逻辑建立在对GC的信任上。
public class UAA {
public static void main(String[] args) {
UAA a = new UAA();
a = null;
System.gc();
while(true);
}
public void finalize(){
System.out.println("finalize!!!! AAAAA");
}
}
为什么这里gc()能马上调用finalize()
System.gc(),同样是一个不可预知的方法,调用该方法即向JVM提出建议:有垃圾,请回收。具体回不回收由JVM的垃圾回收算法决定,我的垃圾回收算法如tracing算法是在cpu出现空闲资源的时候进行回收,找出那些不可达的对象当作垃圾回收,而有些是在内存满的时候回收那些不可达的垃圾对象
你的程序中体现出gc的作用,即它可以建议JVM进行垃圾回收,通过finalize()确保对象的释放,但是这个过程是不确定的。
我觉得调用System.gc()一定马上调用finalize();
但是调用finalize(),不是马上收掉空间。
但回收之前,马上会调用finalize(根据finalize的定义)
考虑复杂情形,大型系统下,jvm会怎么处理……你可以通过jvm参数直接关闭System.gc(),让jvm忽略这个调用。
{
public static void main(String[] args)
{
String a = new String("此对象还未被回收!");
WeakReference b = new WeakReference(a);
System.out.println(b.get());
//移除强引用
a = null;
//呼叫gc
System.gc();
//对象不是应该被finalize?
if(b.get() == null)
System.out.println("对象被回收了!");
else
System.out.println(b.get());
System.exit(0);
}
}
下面的程序可以证明这一点,每次sleep之前的GC调用都导致对象立即被回收。public class GCTest {
public static void main(String[] args) throws InterruptedException {
Obj obj1 = new Obj();
Obj obj2 = new Obj();
System.out.println("begin.");
Thread.sleep(2000);
obj1 = null;
System.gc();
Thread.sleep(2000);
obj2 = null;
System.gc();
Thread.sleep(2000);
System.out.println("end.");
}
}class Obj {
public void finalize() {
System.out.println(this + " is finalized.");
}
}尽管如此,对GC抱不信任态度还是明智的,特别地,不要重要的程序逻辑建立在对GC的信任上。