WeakHashMap in Java

WeakHashMap in Java

A WeakHashMap is a special Map implementation where the keys of the map are stored in WeakReference. By storing the keys in a weak reference, key-value pairs can dynamically be dropped from the map when the only reference to the key is from the weak reference. This makes the WeakHashMap an excellent implementation for a weakly referenced list, where entries that aren’t used elsewhere may be dropped with no side effects.

Weakhashmap allow its entries to be garbage collected rather than waiting for full hashmap to be unused. So, it will automatically remove individual values when its key is no longer in ordinary use.

We can use a WeakHashmap to reduce the chance of a memory leak as a result of caching some object. Some features of WeakHashMap…

  1. WeakHashMap isn’t serialized.
  2. WeakHashMap permits null as key and value.
  3. Insertion order is not maintain in WeakHashMap.

WeakHashMap provides following constructors.

WeakHashMap()Constructs a new, empty WeakHashMap with the default initial capacity (16) and load factor (0.75).
WeakHashMap(Map map)Constructs a new WeakHashMap with the same mappings as the specified map.
WeakHashMap(int initialCapacity)Constructs a new, empty WeakHashMap with the given initial capacity and the default load factor (0.75). Throws IllegalArgumentException if the initial capacity is negative.
WeakHashMap(int initialCapacity, float loadFactor)Constructs a new, empty WeakHashMap with the given initial capacity and the given load factor. Throws IllegalArgumentException if the initial capacity is negative, or if the load factor is nonpositive.

Example of WeakHashMap

package com.code2succeed.collection;

import java.util.WeakHashMap;

public class WeakHashMapExample1 {
	public static void main(String[] args) {
		WeakHashMap<String, String> weakHashMap = new WeakHashMap<String, String>();
		//create key reference
		String weakHashMapKey = new String("weakHashMapKey");
		//create values
		String weakHashMapValue = "weakHashMapValue";
		//store key-value pairs in hashMap and weakHashMap
		weakHashMap.put(weakHashMapKey, weakHashMapValue);
		System.out.println("WeakHashMap : "+weakHashMap);
		System.out.println("Size of WeakHashMap : "+weakHashMap.size());
		//assign null to key references
		weakHashMapKey = null;
		System.out.println("WeakHashMap after garbage collection : "+weakHashMap);
		System.out.println("Size of WeakHashMap after garbage collection: "+weakHashMap.size());


WeakHashMap : {weakHashMapKey=weakHashMapValue}
Size of WeakHashMap : 1
WeakHashMap after garbage collection : {}
Size of WeakHashMap after garbage collection: 0

One thought on “WeakHashMap in Java

Leave a Reply

Your email address will not be published. Required fields are marked *