简体   繁体   English

Java-在程序结束时是否不“收集垃圾”对象?

[英]Java - Objects are not “garbage collected” at the end of the program?

public class Main {

    public static void main(String[] args) throws InterruptedException {
        ClassA a = new ClassA();
        a = null;

        //Runtime.getRuntime().gc();
        Thread.sleep(4000);
    }
}

public class ClassA {

    @Override
    public void finalize(){
        System.out.println("cleaned");
    }  
}

With the above code finalize() never executes. 使用上面的代码,finalize()永远不会执行。 Nothing is printed to the console. 什么都没有打印到控制台。 When Removing comment from gc(), finalize() executes, and "cleaned" is printed to the console. 从gc()删除注释时,将执行finalize(),并将“ cleaned”打印到控制台。 Why do I have to call to the garbage collector explicitly ? 为什么我必须显式调用垃圾收集器?

Finalization is not guaranteed to be executed with the virtual machine exit. 不能保证在虚拟机退出时执行终结处理。 There is no explicit GC for and the finalization is run in a dedicated thread which also exits. 没有显式的GC,并且终结处理在专用线程中运行,该线程也退出。 Link to explanation: http://download.oracle.com/javase/6/docs/api/java/lang/System.html#runFinalizersOnExit%28boolean%29 链接到说明: http : //download.oracle.com/javase/6/docs/api/java/lang/System.html#runFinalizersOnExit%28boolean%29

If you need clean up code use: 如果您需要清理代码,请使用:
Runtime.addShutdownHook http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29 Runtime.addShutdownHook http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM