When to use phantom references in Java? [duplicate]
Asked Answered
K

1

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?

Kosher answered 22/3, 2012 at 16:44 Comment(5)
Or possibly: #1599569Koppel
Short answer: there are almost no applications, other than using it as a better, safer approach to finalization than overriding finalize.Reluctant
@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)Kosher
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.Wirra
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.Linzy
R
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.

Reluctant answered 22/3, 2012 at 17:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.