Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use phantom references in Java? [duplicate]

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?

like image 625
hqt Avatar asked Mar 22 '12 16:03

hqt


People also ask

What is the use of phantom reference in Java?

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.

What are strong soft weak and phantom references in Java?

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.


1 Answers

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.

like image 123
Louis Wasserman Avatar answered Oct 15 '22 03:10

Louis Wasserman