java - 你曾经在任何项目中使用过 PhantomReference 吗?

标签 java reference

关于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”中阅读更多内容)。所以他们也是新的敲定

此外,PhantomReferences

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/

相关文章:

java - XML 解析:如何将 XML 文件中的下一个元素放入字符串中? (Java/安卓)

java - getResource() 在 Gradle 项目中返回 null

java - COMPAS 应用程序被阻止

c++ - C++ 中的临时对象

c++ - 奇怪的编译错误 C++ "undefined reference"& "relocation truncated"

C++ 传递 STL 容器项作为引用

java - 在Java中如何计算目录中具有相同文件扩展名的文件数量?

c++ - 一种在C++中交换两个引用的方法

java - 在 Java 中实现 Clone 有什么替代方法吗?

java - Spring Boot Filter 没有过滤我所有的日志