When to use phantom references in Java?

hqt picture hqt · Mar 22, 2012 · Viewed 9.9k times · Source

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?

Answer

Louis Wasserman picture Louis Wasserman · Mar 22, 2012

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.