WeakHashMap class

In this article, we will discuss WeakHashMap class – one of the Map implemented classes in detail

WeakHashMap is exactly same as that of HashMap with few differences

 

HashMap:

  • If objects don’t have any reference outside of HashMap, even then objects aren’t eligible for Garbage Collection
  • HashMap has precedence over Garbage Collector

 

WeakHashMap:

  • If objects don’t have any reference outside of WeakHashMap, still JVM executes Garbage collection
  • Garbage collector has precedence over objects inside WeakHashMap
  • Kind of stores only weak references

31-WeakHashMap-in-java

Source: Team BenchResources.Net

 

WeakHashMap examples:

WeakHashMapExample.java

package in.bench.resources.java.collection;

import java.util.WeakHashMap;

public class WeakHashMapExample {

	public static void main(String[] args) {

		// creating WeakHashMap object of type <Integer, String>
		WeakHashMap<TempIdClass, String> whm = 
				new WeakHashMap<TempIdClass, String>();

		// creating TempIdClass objects
		TempIdClass temp1 = new TempIdClass(1);
		TempIdClass temp2 = new TempIdClass(2);

		// adding key-value pairs to WeakHashMap object
		whm.put(temp1, "Google");
		whm.put(temp2, "Facebook");

		// deliberately making NULL to test
		temp1 = null;
		temp2 = null;

		// garbage collector
		System.gc();

		System.out.println("Printing WeakHashMap contents : " + whm);
	}
}

class TempIdClass {

	Integer i;

	public TempIdClass(Integer i) {
		super();
		this.i = i;
	}

	@Override
	public String toString() {
		return "TempIdClass [i=" + i + "]";
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		System.out.println("finalize method invoked for "
				+ i + " TempIdClass object");
	}
}

Output:

finalize method invoked for 1 TempIdClass object
finalize method invoked for 2 TempIdClass object
Printing WeakHashMap contents : {}

 

References:

https://docs.oracle.com/javase/tutorial/collections/intro/
https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
http://docs.oracle.com/javase/6/docs/api/java/util/WeakHashMap.html
https://docs.oracle.com/javase/7/docs/api/java/util/WeakHashMap.html

 

Happy Coding !!
Happy Learning !!

SortedMap interface
IdentityHashMap class