WeakReference and WeakHashMap in Java

Weak Reference :
An Object will not be garbage collected if one or more reference exits. This is not true always if the references are Weak Reference then its a valid candidate of Garbage Collection.

four types of references in Java i.e. strong reference, soft reference, weak reference and phantom reference. We will discuss about these references later.

Lets start with an example to understand Weak Reference.
Suppose you have a requirement to store current Active visitors with the entry time.

package in.bibek;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

public class WeakReference

  public static void main(String[] args)
	  Map activeVisitors = new HashMap(); 
	  Visitor v1 = new Visitor(1,"Bibek");
	  activeVisitors.put(v1, new Date());
	  Visitor v2 = new Visitor(2,"Anil");
	  activeVisitors.put(v2, new Date());
	  Visitor v3 = new Visitor(3,"Sachin");
	  activeVisitors.put(v3, new Date());
	  //Now lets say Bibek left so v1 will be null
	  v1 = null;
	  //Request for gc
	 System.out.println("Size "+activeVisitors.keySet().size());

class Visitor
	private int vistiorId;
	private String visitorName;
	Visitor(int id,String name)
		vistiorId = id;
		visitorName = name;		

Now you can see v1 left but the entry still exist in HashMap. So it shouldn’t exist in the Map and v1 should get garbage collected but this will not because its a strong reference.

The output to above program will be

Size 3 

Where as if you change the HashMap to WeakHashMap(Predefined Map which uses weak reference.there is a private method name expungeStaleEntries(), which is used to remove stale entries as given in above example and this method is used in all exposed methods of WeakHashMap) .

Note :System.gc() is a request not a command but by JVM respects my request 🙂


Map activeVisitors = new WeakHashMap(); 

The output will be as below

Size 2

So you can use WeakHashMap whenever entries are no more used. Bit of google will help to understand it better.

One thought on “WeakReference and WeakHashMap in Java

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: