你曾经在任何项目中使用过 PhantomReference 吗? [英] Have you ever used PhantomReference in any project?

查看:19
本文介绍了你曾经在任何项目中使用过 PhantomReference 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于PhantomReference,我唯一知道的是,

The only thing I know about PhantomReference is,

  • 如果您使用它的 get() 方法,它将始终返回 null 而不是对象.有什么用?
  • 通过使用PhantomReference,您可以确保对象不能从finalize 方法中复活.
  • If you use its get() method, it will always return null and not the object. What's the use of it?
  • By using PhantomReference, you make it sure that the object cannot be resurrected from finalize method.

但是这个概念/类有什么用?

But what is the use of this concept/class?

你有没有在你的任何项目中使用过这个,或者你有任何我们应该使用它的例子吗?

Have you ever used this in any of your project or do you have any example where we should use this?

推荐答案

我在 简单的、非常专业的内存分析器,用于监控对象的创建和销毁.我需要它们来跟踪破坏情况.但这种方法已经过时了.(它是在 2004 年针对 J2SE 1.4 编写的.)专业的分析工具更加强大和可靠,更新的 Java 5 特性,如 JMX 或代理和 JVMTI 也可以用于此目的.

I used PhantomReferences in a simplistic, very specialized kind of memory profiler to monitor object creation and destruction. I needed them to keep track of destruction. But the approach is out-dated. (It was written in 2004 targeting J2SE 1.4.) Professional profiling tools are much more powerful and reliable and the newer Java 5 features like JMX or agents and JVMTI can be used for that too.

PhantomReference(总是与引用队列一起使用)优于 finalize,后者有一些问题,因此应该避免.主要是使对象再次可达.这可以通过终结器监护人习语来避免(-> 阅读Effective Java"中的更多内容).所以它们也是新的定稿.

PhantomReferences (always used together with the Reference queue) are superior to finalize which has some problems and should therefore be avoided. Mainly making objects reachable again. This could be avoided with the finalizer guardian idiom (-> read more in 'Effective Java'). So they are also the new finalize.

此外,PhantomReferences

允许您准确确定对象何时从内存中移除.他们事实上,这是确定这一点的唯一方法.这一般不是有用,但在某些非常特殊的情况下可能会派上用场就像处理大图像:如果你确定一个图像应该是垃圾收集,您可以等到它实际上是在尝试之前加载下一个图像,从而减少可怕的 OutOfMemoryError可能.(引自 enicholas.)

allow you to determine exactly when an object was removed from memory. They are in fact the only way to determine that. This isn't generally that useful, but might come in handy in certain very specific circumstances like manipulating large images: if you know for sure that an image should be garbage collected, you can wait until it actually is before attempting to load the next image, and therefore make the dreaded OutOfMemoryError less likely. (Quoted from enicholas.)

正如 psd 首先写的那样,Roedy Green 有一个 很好的参考资料摘要.

And as psd wrote first, Roedy Green has a good summary of references.

这篇关于你曾经在任何项目中使用过 PhantomReference 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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