Home  >  Core Java

Example of SoftReference in Java

By Arvind Rai, January 06, 2012
1. SoftReference belongs to the package java.lang.ref.
2. SoftReference objets can be garbage collected if memory is demanded.
3. Before throwing OutOfMemoryError, Garbage collector checks for soft references and if available, garbage collector gets memory from garbage collecting soft reference.
4. SoftReference has only one method that is get method.
Objects are created as
SoftReference(Object referent)

SoftReference(Object referent,ReferenceQueue rq)
package com.concretepage;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
public class SoftReferenceTest {
	public static void main(String... args){
		ReferenceQueue rq= new ReferenceQueue(); 
		A a= new A();
		a.s="hello";
		Reference r= new SoftReference(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
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us