敲定方法中的异常 [英] Exception in finalize method

查看:116
本文介绍了敲定方法中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

方法finalize和异常





$ b 垃圾收集器调用<$ c $当一个对象即将从内存释放时,c> finalize()方法。在 finalize()方法中引发异常时会发生什么?



GC是否会继续进行并释放内存,或GC会停止该对象的进程?

解决方案

如果在try-catch语句中引发异常并且正确然后是的,GC将继续进行下去,就像它在常规程序中一样。



但是如果抛出的异常没有被处理,那么根据 JSL


如果在终止期间抛出未捕获的异常,则该异常将被忽略,并且该对象的终止将终止。因此,在这种情况下,GC将停止该对象的进程,在这种情况下,它可能是某些资源

顺便说一句,终结者有两个缺点:$ b​​
$ b $ ul

  • 你不能确定finalize方法会被执行(来自 this blog
    $ b


    为什么上面的垃圾收集器总是会调用finalize,然后释放与目的?原因是垃圾收集器并不总是有机会在JVM终止之前清理对象。



  • 终结器强制对象被提升到旧空间(需要更长的时间来收集),并推迟GC直到终结器运行,这会增加GC算法的开销。 (请参阅Jack Shirazi编辑的Java performance Tuning 2nd)。



  • Possible Duplicate:
    method finalize and exceptions

    The garbage collector invokes finalize() method when an object is about to released from memory. What happens when an exception is raised in the finalize() method?

    Will GC proceed further and release the memory, or GC will halt the process for that object?

    解决方案

    If the exception is raised in a try-catch statement and is correctly caught then yes, "the GC will proceed further", as it does in regular programs.

    But if the thrown exception is not handled then, according to the JSL,

    If an uncaught exception is thrown during the finalization, the exception is ignored and finalization of that object terminates.

    So, in this case the "GC will halt the process for that object" and in which case it may be that some its resources are not have been correctly released.

    By the way, the finalizer has 2 drawbacks :

    • You cannot be sure that the finalize method will be ever be executed (from this blog)

      Why do the above if the garbage collector will always call finalize before freeing up memory associated with an object? The reason is because the garbage collector doesn't always get a chance to clean up objects before the JVM terminates.

    • Finalizers force objects to be promoted to old space (that takes longer to collect), and postpone the GC until the finalizer is run, adding more overhead to the GC algotithm. (cf Java performance Tuning 2nd,Edition by Jack Shirazi).

    这篇关于敲定方法中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆