Java WeakHashMap Real-Time Example

In this source code example, you will learn how to use the WeakHashMap class in real-time Java projects.

WeakHashMap is a specialized implementation of the Map interface from java.util package where keys are stored as weak references. If a key is not referred to outside of the WeakHashMap, it can be garbage collected, and its entry is removed from the map.

Real-World Use Case: Java WeakHashMap in Cache Implementation

The primary use case of WeakHashMap is to build cache systems where you don't want the cache to prevent its keys from being garbage collected. If a key is no longer in use or referenced outside of the WeakHashMap, it can be garbage collected, thus not causing memory leaks in caching scenarios.

import java.util.WeakHashMap;

public class CacheSystem {

    // Define a simple cache using `WeakHashMap`
    private final WeakHashMap<Object, String> cache = new WeakHashMap<>();

    // Method to add item to cache
    public void addToCache(Object key, String value) {
        cache.put(key, value);
    }

    // Method to get item from cache
    public String getFromCache(Object key) {
        return cache.getOrDefault(key, "Not Found");
    }

    public static void main(String[] args) throws InterruptedException {
        CacheSystem cacheSystem = new CacheSystem();

        // 1. Adding entries to the cache
        Object obj1 = new Object();
        Object obj2 = new Object();

        cacheSystem.addToCache(obj1, "Data for obj1");
        cacheSystem.addToCache(obj2, "Data for obj2");
        System.out.println("1. Cache after adding entries: " + cacheSystem.cache);

        // 2. Nullifying reference and invoking garbage collector
        obj1 = null;
        System.gc();
        Thread.sleep(500);  // giving some time for garbage collector to work

        System.out.println("2. Cache after nullifying a reference and calling GC: " + cacheSystem.cache);
    }
}

Output:

1. Cache after adding entries: {java.lang.Object@XYZ=Data for obj1, java.lang.Object@ABC=Data for obj2}
2. Cache after nullifying a reference and calling GC: {java.lang.Object@ABC=Data for obj2}
(Note: Object hash codes XYZ and ABC will be different for each run)

Explanation:

1. Initialized a simple cache system using WeakHashMap where the keys represent the objects we want to keep track of, and values are the associated cached data.

2. Added two objects (obj1 and obj2) and their corresponding data to the cache.

3. To simulate cache eviction, we nullified the reference of obj1 and invoked the garbage collector. Since WeakHashMap does not prevent its keys from being garbage collected, after garbage collection, the entry corresponding to the nullified reference (obj1) gets removed automatically.

The primary use case of WeakHashMap is to build cache systems where you don't want the cache to prevent its keys from being garbage collected. If a key is no longer in use or referenced outside of the WeakHashMap, it can be garbage collected, thus not causing memory leaks in caching scenarios.


Comments