Phantom reference
A phantom reference is a kind of reference in Java, where the memory can be reclaimed. The class is 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. UsePhantom references are of limited use, primarily narrow technical uses.[3] First, it can be used instead of a Exampleimport java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
class Resource {
private final String name;
public Resource(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class PhantomReferenceExample {
public static void main(String[] args) throws InterruptedException {
Resource resource = new Resource("My resource");
ReferenceQueue<Resource> queue = new ReferenceQueue<>();
PhantomReference<Resource> phantomRef = new PhantomReference<>(resource, queue);
resource = null;
System.gc();
Reference<? extends Resource> ref = queue.poll();
if (ref != null) {
System.out.printf("Object is ready to be collected: %s%n", ((PhantomReference<?>)ref).get());
}
}
}
See alsoReferences
|