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?
Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed. Phantom references are most often used for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.
An object that is reachable via phantom references will remain so until all such references are cleared or themselves become unreachable. So in brief: Soft references try to keep the reference. Weak references don't try to keep the reference. Phantom references don't free the reference until cleared.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With