When to use phantom references in Java? [duplicate]

别等时光非礼了梦想. 提交于 2019-11-27 15:53:44

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9826741/when-to-use-phantom-references-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!