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

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

问题描述

我已经阅读了不同类型的参考资料.我了解强引用、软引用和弱引用的工作原理.

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();
}
...

这或多或少类似于这篇文章 建议.

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

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

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