简体   繁体   English

finalize方法如何与Java中的幻影引用一起使用

[英]How finalize method works with phantom reference in java

Hi I have one doubt about phantom reference. 嗨,我对幻影参考存在疑问。 What I understand the finalize method is called just before when object are going for garbage collection. 我了解的finalize方法在对象要进行垃圾回收之前被调用。 But some time if object are not eligible for garbage collection then finalize method will not execute. 但是一段时间后,如果对象不符合垃圾回收的条件,则finalize方法将无法执行。

Now talking about phantom reference when this finalize method will called. 现在讨论何时调用此finalize方法的幻影引用。

Is finalize always called in phantom reference. 定型总是在幻象引用中调用。

I am very much confuse about this. 我对此非常困惑。 Please help me. 请帮我。

Finalizers are never guaranteed to be called, whether there is a phantom reference or not. 无论是否有幻像引用,都不能保证一定要调用终结器。 Don't rely on finalizers for any critical part of your code because there is no guarantee that they will be called in a timely manner or in fact at all. 不要依赖终结器来处理代码的任何关键部分,因为不能保证会及时或实际上不会调用终结器。

Many people advocate that you simply should never use finalizers at all because they are incredibly difficult to use correctly. 许多人主张,你根本应该在所有的,因为他们是非常困难的正确使用使用终结。

When object becomes available only through phantom reference then after the first GC finalize() method is invoked and after the second GC the reference is enqueued. 当对象仅通过幻像引用变为可用时,则在调用第一个GC finalize()方法之后,在第二个GC之后,将引用加入队列。 If after that phantom reference is cleaned (or becomes unavailable itself) then the memory is cleared after the third GC. 如果该幻影引用被清除后(或本身不可用),则在第三个GC之后清除内存。

Finalize will always be called, but not neccessarely, when you expect it. 当您期望时,将始终调用Finalize,但不一定调用它。 It may happen, that the call will only be made at the JVM shutdown (assuming you don't simply kill the program). 可能会发生这种情况,即仅在JVM关闭时才进行调用(假设您不会简单地杀死程序)。 You should not rely on finalize() in order to do significant work. 您不应该依赖finalize()来进行大量工作。 But it is also good practice to implement a usefull finalize() and include a call to super.finalize() too. 但是,实现有用的finalize()并包含对super.finalize()的调用也是一种好习惯。

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

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