gpt4 book ai didi

java - Java 内存泄漏 : finalization? 故障排除

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:28 29 4
gpt4 key购买 nike

我有一个行为不端的应用程序,似乎在泄漏。经过简短的探查器调查后,大部分内存 (80%) 由 java.lang.ref.Finalizer 实例占用。我怀疑终结器无法运行。

一个常见的原因似乎是终结器抛出的异常。然而,Object 类的 finalize 方法的 javadoc(例如参见 here)似乎自相矛盾:它指出

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

但后来,它还指出

Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.

我应该相信什么(即定稿是否停止?),关于如何调查此类明显的泄漏,您有什么建议吗?

谢谢

最佳答案

两个引号都说:

An exception will cause finalization of this object to be halted/terminated.

这两段引文还说:

The uncaught exception is ignored (i.e. not logged or handled by the VM in any way)

这样就回答了你问题的前半部分。不过,我对 Finalizers 的了解还不够多,无法为您提供有关追踪内存泄漏的建议。

编辑:我找到了 this page这可能有用。它有一些建议,例如在终结器中手动将字段设置为 null 以允许 GC 回收它们。

EDIT2:一些更有趣的链接和引用:

来自 Anatomy of a Java Finalizer

Finalizer threads are not given maximum priorities on systems. If a "Finalizer" thread cannot keep up with the rate at which higher priority threads cause finalizable objects to be queued, the finalizer queue will keep growing and cause the Java heap to fill up. Eventually the Java heap will get exhausted and a java.lang.OutOfMemoryError will be thrown.

还有

it's not guaranteed that any objects that have a finalize() method are garbage collected.

EDIT3:在阅读更多 Anatomy 链接后,似乎在 Finalizer 线程中抛出异常确实会减慢它的速度,几乎与调用 Thread.yield() 一样多。您似乎是对的,即使抛出异常,Finalizer 线程最终也会将对象标记为能够进行 GC。但是,由于减速很明显,在您的情况下,Finalizer 线程可能跟不上对象创建和超出范围的速率。

关于java - Java 内存泄漏 : finalization? 故障排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7644556/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com