Saturday 26 July 2014

Weak Reference in Java

If an object has only weak references associated with it, then Garbage collector permitted to reclaim the memory used by the object. Weak References to an object are created using WeakReference class.

class Employee{
    String name;
    int id;
    
    Employee(int id, String name){
        this.id =id;
        this.name = name;
    }
        
    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();
        }
    }
}

import java.lang.ref.*;

public class WeakReferenceEx {
    public static void main(String args[]) throws InterruptedException{
        Employee emp1 = new Employee(1, "Krishna");
        WeakReference<Employee> weakRef = new WeakReference<>(emp1);
        
        System.out.println("Calling Garbage collector");
        System.gc();
        System.out.println("Waiting for 1 second");
        Thread.sleep(1000);
        
        System.out.println("Setting emp1 to null");
        emp1 = null;
        System.gc();
        Thread.sleep(1000);
    }
}

Output
Calling Garbage collector
Waiting for 5 seconds
Setting emp1 to null
1 Krishna is going to be garbage collected

Application creates Employee object and emp1 is strong reference to the object.
Employee emp1 = new Employee(1, "Krishna")

Below statement assign a weak reference to the same object
WeakReference<Employee> weakRef = new WeakReference<>(emp1);

As you observe the program, Garbage collector won't clear the employee object, until it has strong reference to it. It clears the memory occupied by the Employee object, once emp set to null, even though it has weak reference to it.

If Garbage collector detects a weekly reachable object, then
  1. Weak reference object referent field is set to null.
  2. The heap object that is referenced by the WeakReference is declared finalizable.
  3. When the heap object's finalize() method is run and its memory freed, the WeakReferenceobject is added to its ReferenceQueue, if it exists.
import java.lang.ref.*;

public class WeakReferenceEx {
    
    static WeakReference<Employee> weakRef;
    
    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");
        weakRef = new WeakReference<>(emp1);
        
        System.out.println("Calling Garbage collector");
        System.gc();
        System.out.println("Waiting for 5 seconds");
        Thread.sleep(1000);
        
        System.out.println("Setting emp1 to null");
        emp1 = null;
        System.gc();
        System.out.println("Referent field value is "+weakRef.get());
    }
}

Output
Calling Garbage collector
Waiting for 5 seconds
Setting emp1 to null
Referent field value is null
1 Krishna is going to be garbage collected

Observe the output referent field is set to null, before calling finalize method.









Prevoius                                                 Next                                                 Home

No comments:

Post a Comment