Home  >  Core Java

Examples of WeakReference in Java

By Arvind Rai, January 06, 2012
1. WeakReference belongs to package java.lang.ref.
2. WeakReference objects are weakly reachable. Weakly reachable means objects are neither strongly nor softly reachable.
3. When weak references to weakly reachable objects are cleared then that object is eligible to garbage collected.
4. Methods are inherited from java.lang.ref.Reference. Those methods are get,enqueue,get,isEnqueued.

Objects are created as
 WeakReference(Object referent)
 
For the given referent object, it creates the weak reference object. Another way is
WeakReference(Object referent, ReferenceQueue q)
package com.concretepage;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
public class WeakReferenceTest {
	public static void main(String... args){
		ReferenceQueue<A> rq= new ReferenceQueue<A>(); 
		A a= new A();
		a.s="hello";
		Reference<A> r= new WeakReference<A>(a,rq);
		a=null;
		System.gc();	
		Reference ref=  rq.poll();
		System.out.println(ref);
		while(ref!=null){
			System.out.println(ref.get());
		}
	}
}
class A{
	String s;
}
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us