18

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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
hqt
  • 29,632
  • 51
  • 171
  • 250
  • Or possibly: http://stackoverflow.com/questions/1599069/have-you-ever-used-phantom-reference-in-any-project – Brendan Long Mar 22 '12 at 16:47
  • Short answer: there are almost no applications, other than using it as a better, safer approach to finalization than overriding `finalize`. – Louis Wasserman Mar 22 '12 at 17:22
  • @LouisWasserman can you give me a detail example,please. I hope to see it. thanks :) (just give me how use phantom reference instead of finalize) – hqt Mar 22 '12 at 17:24
  • I'm looking into using Phantom references in a JOGL project to automatically delete buffers, textures, etc. that were created in video memory when they are no longer in use. Although a Java object that allocated video memory may get garbage collected, the memory it allocated would not, it has to be deallocated manually. Overriding the finalize() method of the object would not work because GL is not available at any time; however, a phantom reference to the object could tell the GL thread to free the memory next time it is running. – Andy May 03 '14 at 01:56
  • I have used it to track down memory leaks. I watch suspected objects to see when they get garbage collected. It's been very helpful for that. – MiguelMunoz Sep 28 '21 at 03:21

1 Answers1

11

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413