Home  >  Core Java

Example of PhantomReference in Java

By Arvind Rai, January 03, 2013
1. PhantomReference belongs to the package java.lang.ref.Reference and is available from jdk1.2.
2. PhantomReference objects are phantom reachable. Phantom reachable objects are those objects which are neither strongly, softly nor weakly reachable.
3. Garbage collector does not clear phantom reference automatically. PhantomReference objects are enqueued in ReferenceQueue.
4. PhantomReference has get method. It returns objectís referent.
package com.concretepage;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;

public class PhantomReferenceTest {
	public static void main(String... args){
		ReferenceQueue rq= new ReferenceQueue(); 
		A a= new A();
		a.s="hello";
		Reference r= new PhantomReference(a,rq);
		a=null;
		System.gc();	
		Reference ref= (Reference) rq.poll();
		while(ref!=null){
			System.out.println(ref.get());
		}
	} 
}
class A{
	String s;
}
POSTED BY
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us