关于Java中System.gc() 与System.runFinalization()
System.gc :
告诉垃圾收集器打算进行垃圾收集,而垃圾收集器进不进行收集是不确定的。只是建议进行回收
System.runFinalization():
网上搜了一下很多人都说强制调用已经失去引用的对象的finalize方法。但是我用下边的程序测试了一下
class Chair{ public int i; public static int created = 0; public Chair() { i = ++created; } @Override protected void finalize() throws Throwable { System.out.println("第" + i +"个Chair调用finalize方法"); } } public class Garbage{ public static void main(String[] args) { for (int i = 0; i < 47; ++i) { new Chair(); //System.out.println("runfinalize"); System.runFinalization(); //System.gc(); } } }
显然我们每次new出来的Chair都已经都已经没有引用了,但是调用System.runFinalization();这些没有引用的对象还是不调用finalize这个函数,很奇怪,然后就已知搜,然后看到的仍让是很多说的强制执行。
后来看了一下JDK里面的说明:
Calling this method suggests that the Java Virtual Machine expend * effort toward running the <code>finalize</code> methods of objects * that have been found to be discarded but whose <code>finalize</code> * methods have not yet been run. When control returns from the * method call, the Java Virtual Machine has made a best effort to 注意是suggest that 同gc一样都是建议JVM。 所以JVM可以选择执行或者不执行