문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top