public
WeakReference(T referent, ReferenceQueue<? super T> q)
Creates
a new weak reference that refers to the given object and is
registered with the given queue.
import java.lang.ref.*; public class WeakReferenceEx1 { static WeakReference<Employee> weakRef1; static WeakReference<Employee> weakRef2; static ReferenceQueue<Employee> refQueue = new ReferenceQueue(); static class Employee{ String name; int id; Employee(int id, String name){ this.id =id; this.name = name; } @Override public String toString(){ return id +" " + name; } @Override protected void finalize() throws Throwable{ try { System.out.println(this + " is going to be garbage collected"); } finally { super.finalize(); } } } public static void main(String args[]) throws InterruptedException{ Employee emp1 = new Employee(1, "Krishna"); Employee emp2 = new Employee(1, "Hari"); weakRef1 = new WeakReference<>(emp1, refQueue); weakRef2 = new WeakReference<>(emp2, refQueue); System.out.println("Calling Garbage collector"); System.gc(); System.out.println("Waiting for 1 second"); Thread.sleep(1000); System.out.println("Setting emp1 and emp2 to null"); emp1 = null; emp2 = null; System.gc(); System.out.println("weakRef1 referent value is "+weakRef1.get()); System.out.println("weakRef2 referent value is "+weakRef2.get()); Thread.sleep(1000); System.out.println("weakRef1 = " + weakRef1); System.out.println("weakRef2 = " + weakRef2); System.out.println(refQueue.poll()); System.out.println(refQueue.poll()); System.out.println(refQueue.poll()); } }
Output
Calling Garbage collector Waiting for 1 second Setting emp1 and emp2 to null weakRef1 referent value is null weakRef2 referent value is null 1 Hari is going to be garbage collected 1 Krishna is going to be garbage collected weakRef1 = java.lang.ref.WeakReference@1db9742 weakRef2 = java.lang.ref.WeakReference@106d69c java.lang.ref.WeakReference@106d69c java.lang.ref.WeakReference@1db9742 null
No comments:
Post a Comment