jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Phantom  Reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Phantom  Reference" Watch "Phantom  Reference" New topic

Phantom Reference

Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8927

What is phantom reference and how is different from soft or weak reference

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
i think the java docs from sun say it best:
"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."
this is from http://java.sun.com/j2se/1.4/docs/api/java/lang/ref/PhantomReference.html
and to the last part of your question, the same source goes on to say
"Unlike soft and weak references, phantom references are not automatically cleared by the garbage collector as they are enqueued. An object that is reachable via phantom references will remain so until all such references are cleared or themselves become unreachable."
Zakaria Haque
Ranch Hand

Joined: Jan 02, 2002
Posts: 60
gc clears soft or weak references before they are enqued, but phantom references are never cleared by gc. you have to get the object from the associated reference queue and call the clear method yourself. The benefit is, with PhantomReference you can do some fine-grain cleanup before the object is reclaimed by gc, which you can not do with other references(since they are alreasy cleared). Note that, the referent object can be finalized(but not reclaimed) before the phantom reference is enqueued.
If you are working with references, watch that gc may not call the clear method of the API to clear a object. That is, if you subclass any of the reference classes and override the clear method, dont expect it to execute when the gc is clearing the object.
Feel free to ask if this is not clear.

tobe bondhu nouka bherao<br />shonabo gaan aj shara raat
I agree. Here's the link: http://aspose.com/file-tools
subject: Phantom Reference
It's not a secret anymore!