This article needs additional citations for verification .(May 2009) |
A phantom reference is a kind of reference in Java, where the memory can be reclaimed. The class is java.lang.ref.PhantomReference
. The phantom reference is one of the strengths or levels of 'non strong' reference defined in the Java programming language; the others being weak and soft. [1] Phantom reference are the weakest level of reference in Java; in order from strongest to weakest, they are: strong, soft, weak, phantom.
An object is phantomly referenced after it has been finalized.
In Java 8 and earlier versions, the reference needs to be cleared before the memory for a finalized referent can be reclaimed. A change in Java 9 [2] will allow memory from a finalized referent to be reclaimable immediately.
Phantom references are of limited use, primarily narrow technical uses. [3] First, it can be used instead of a finalize
method, guaranteeing that the object is not resurrected during finalization. This allows the object to be garbage collected in a single cycle, rather than needing to wait for a second GC cycle to ensure that it has not been resurrected. A second use is to detect exactly when an object has been removed from memory (by using in combination with a java.lang.ref.ReferenceQueue
object), ensuring that its memory is available, for example deferring allocation of a large amount of memory (e.g., a large image) until previous memory is freed.
importjava.lang.ref.PhantomReference;importjava.lang.ref.ReferenceQueue;classResource{privatefinalStringname;publicResource(Stringname){this.name=name;}publicStringgetName(){returnname;}}publicclassPhantomReferenceExample{publicstaticvoidmain(String[]args)throwsInterruptedException{Resourceresource=newResource("My resource");ReferenceQueue<Resource>queue=newReferenceQueue<>();PhantomReference<Resource>phantomRef=newPhantomReference<>(resource,queue);resource=null;System.gc();Reference<?extendsResource>ref=queue.poll();if(ref!=null){System.out.printf("Object is ready to be collected: %s%n",((PhantomReference<?>)ref).get());}}}