Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Phantom Reference

 
Pradeep bhatt
Ranch Hand
Posts: 8933
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is phantom reference and how is different from soft or weak reference
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic