Core Java

WeakHashMap In Java

Introduction:

WeakHashMap in Java is a pretty popular data-structure among mid to senior-level Java developers.

The WeakHashMap class is present in the java.util package. It’s a Map implementation which stores weak references to its keys. An entry in a WeakHashMap gets automatically removed when the associated key loses all of its active strong and soft references.

In this post, we’ll first talk about the types of references in Java – Soft, Weak, and Strong references. And then, we’ll learn about the WeakHashMap.

Types Of Java References:

Java allows having three different types of references:

1. Strong References:

Strong references are the ones we use in our day-to-day Java programming:

Any object that is being referenced by a strong reference isn’t eligible for garbage collection.

2. Soft References:

An object pointed by a soft reference won’t be garbage collected until the JVM is in absolute need of memory. We can create a java.lang.ref.SoftReference, such as:

3. Weak References:

We can create a WeakReference using java.lang.ref.WeakReference class. Any object which loses all strong and soft references will immediately become eligible for garbage collection, even when we have a few weak references pointing to it:

Constructing WeakHashMap:

A Java WeakHashMap is a hashing implementation which holds WeakReference for its keys. Just like a HashMap, it also supports a null key and null values. We can create a WeakHashMap using one of the available constructors:

  • WeakHashMap(): creates an empty WeakHashMap with a default capacity(16) and a default load-factor(0.75)
  • WeakHashMap(int initialCapacity): creates an empty WeakHashMap with given capacity and default load-factor
  • WeakHashMap(int initialCapacity, float loadFactor): uses the given initial capacity and load-factor to instantiate a WeakHashMap
  • WeakHashMap(Map<? extends K,? extends V> map): constructs a new WeakHashMap with the same mappings as the specified Map

Let’s quickly instantiate a WeakHashMap using the default constructor:

Methods In WeakHashMap:

A WeakHashMap implements Map interface and so inherits all of its methods. Let’s look at the most commonly used methods:

  • V put(K key, V value): inserts a new key-value pair in a WeakHashMap. If the map already contains the given key, its value is replaced
  • V get(Object key): retrieves the value of the given key. It returns null if the map contains no mapping for the key
  • V remove(Object key): removes the entry with a given key and returns the associated value
  • boolean containsKey(Object key): returns true if the map contains a given key, false otherwise
  • boolean containsValue(Object value): checks whether the map contains the given value
  • int size(): gets the size of the WeakHashMap
  • boolean isEmpty(): returns whether the map is empty or not
  • Set<Map.Entry<K, V>> entrySet(): returns a Set view of mappings contained in the map
  • Set<K> keySet(): returns a Set view of keys contained in the map
  • Collection<V> values(): returns a Collection view of values contained in the map

Let’s try out a few of these methods:

How WeakHashMap works?

We earlier discussed that a WeakHashMap, unlike a HashMap, stores weak references of keys.

Let’s now try to understand this concept with the help of an example.

Suppose we have an Employee class:

And say we define a WeakHashMap<Employee, Integer> which stores count of dependants for each Employee:

Clearly, we can see that now our WeakHashMap no longer contains an entry for sierra. In other words, the object pointed by sierra lost its only strong reference when we set it to null and became eligible for garbage collection. On requesting garbage collection using System.gc(), the garbage collector removed that entry from the WeakHashMap.

HashMap vs WeakHashMap:

Let’s discuss the important differences between a HashMap and a WeakHashMap:

HashMapWeakHashMap
The stored entry object is not eligible for garbage collectionAn entry in a WeakHashMap will be automatically removed when its key loses all strong and soft references
HashMap holds strong references for its key objectsWeak references to keys are stored in case of a WeakHashMap
The size() method will always return the same value unless we explicitly add or remove entriesThe size() method may return smaller value as a few entries might automatically be removed by GC
HashMap implements Cloneable interface and its clone() method returns a shallow copy of the HashMapDoesn't implements Cloneable
Implements Serializable interfaceDoesn't supports serialization

Conclusion:

In this tutorial, we learned about a WeakHashMap in Java. WeakHashMap stores weak references to its key objects and so the entries may get automatically removed once the key loses all usual references.

 

Be the First to comment.

Leave a Comment

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