Home » Java » Core Java » WeakHashMap In Java

About Shubhra Srivastava

Shubhra Srivastava
Shubhra is a software professional and founder of ProgrammerGirl. She has a great experience with Java/J2EE technologies and frameworks. She loves the amalgam of programming and coffee :)

WeakHashMap In Java

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:

Employee emp = new Employee("Jake");

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:

SoftReference<Employee> empSoft = new SoftReference<>(new Employee("Jake"));

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:

Employee jake = new Employee("Jake");
Employee jakeOtherStrongRef = jake;
 
WeakReference<Employee> emp = new WeakReference<>(jake);
 
jake = null; // object not yet eligible for GC as jakeOtherStrongRef also exists
jakeOtherStrongRef = null; //object is now eligible for GC

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:

WeakHashMap<Integer, String> map = new WeakHashMap<>();

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:

map.put(1, "Argon");
map.put(2, "Nitrogen");
 
System.out.println(map.containsKey(1)); //true
System.out.println(map.containsKey(3)); //false
System.out.println(map.containsValue("Nitrogen")); //true
 
String val = map.get(2); // "Nitrogen" 
int size = map.size(); //2
 
for(Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ":" + entry.getValue());
}

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:

class Employee {
 
    private int id;
    private String name;
 
    //constructors, getters and setters
    
    public String toString() {
        return "[Employee{id=" + id + " ,name=" + name + "}]";
    }
}

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

Map<Employee, Integer> weakHashMap = new WeakHashMap<>();
 
Employee ray = new Employee(1, "Ray");
Employee sierra = new Employee(2, "Sierra");
 
weakHashMap.put(ray, 3);
weakHashMap.put(sierra, 4);
 
System.out.println(weakHashMap); 
 //{[Employee{id=1 ,name=Ray}]=3, [Employee{id=2 ,name=Sierra}]=4} 
 
sierra = null;
 
System.gc();
 
System.out.println(weakHashMap); //{[Employee{id=1 ,name=Ray}]=3}

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.

Published on Java Code Geeks with permission by Shubhra Srivastava, partner at our JCG program. See the original article here: WeakHashMap In Java

Opinions expressed by Java Code Geeks contributors are their own.

(+2 rating, 2 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply

avatar

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

  Subscribe  
Notify of