何时在Java中使用幻像引用? [英] When to use phantom references in Java?

查看:342
本文介绍了何时在Java中使用幻像引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

你有没有在任何项目中使用Phantom参考?

我已经阅读了不同类型的参考资料。我理解强大,柔软和弱的引用是如何工作的。

I have read about the different types of reference. I understand how strong, soft and weak references work.

但是当我读到有关幻像引用时,我无法理解它们。也许是因为我找不到任何好的例子来告诉我他们的目的是什么或何时使用它们。

But when I read about phantom references, I could not really understand them. Maybe because I could not find any good examples that show me what their purpose is or when to use them.

你能告诉我一些使用幻像参考的代码示例吗?

Could you show me some code examples that use a phantom reference?

推荐答案

我自己从未这样做过 - 很少有人需要它 - 但我认为这是一种方法。

I've never done this myself -- very few people ever need it -- but I think this is one way to do it.

abstract class ConnectionReference extends PhantomReference<Connection> {
  abstract void cleanUp();
}
...
ReferenceQueue<Connection> connectionQueue = new ReferenceQueue<>();
...
Connection newConnection = ...
ConnectionReference ref = new ConnectionReference(newConnection, connectionQueue, ...);
...
// draining the queue in some thread somewhere...
Reference<? extends Connection> reference = connectionQueue.poll();
if (reference != null) {
  ((ConnectionReference) reference).cleanUp();
}
...

这或多或少类似于< a href =http://weblogs.java.net/blog/kcpeppe/archive/2011/09/29/mysterious-phantom-reference>这篇文章建议。

This is more or less similar to what this post suggests.

这篇关于何时在Java中使用幻像引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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