关于PhantomReference
,我唯一知道的是,
- 如果你使用它的
get()
方法,它总是返回null
而不是对象。有什么用? - 通过使用
PhantomReference
,您可以确保对象无法通过finalize
方法复活。
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?
最佳答案
我在 simplistic, very specialized kind of memory profiler 中使用了 PhantomReference
监控对象的创建和销毁。我需要他们跟踪破坏。但这种方法已经过时了。 (它是在 2004 年针对 J2SE 1.4 编写的。)专业的分析工具更加强大和可靠,并且 JMX 或代理和 JVMTI 等较新的 Java 5 功能也可以用于此目的。
PhantomReference
(总是与引用队列一起使用)优于 finalize
,后者存在一些问题,因此应避免使用。主要是使对象再次可达。这可以通过终结器监护人习语来避免(-> 在“有效 Java”中阅读更多内容)。所以他们也是新的敲定。
此外,PhantomReference
s
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 有一个 good summary of references .
关于java - 你曾经在任何项目中使用过 PhantomReference 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1599069/