Search code examples
javacachingconcurrenthashmap

What is the use case of WeakCache in Java?


What are the use cases of WeakCache in Java?


Solution

  • By default, in a Hashmap, when the reference to a value is found to have been cleared, the corresponding key is removed. This class provides essentially a map with strongly referenced keys and weakly referenced values. Getting a value whose reference has been cleared gets null.

    Let's say that we want to build a cache that keeps big image objects as values, and image names as keys. We want to pick a proper map implementation for solving that problem.

    Using a simple HashMap will not be a good choice because the value objects may occupy a lot of memory. What's more, they'll never be reclaimed from the cache by a GC process, even when they are not in use in our application anymore.

    Ideally, we want a Map implementation that allows Garbage Collector to automatically delete unused objects. When a key of a big image object is not in use in our application in any place, that entry will be deleted from memory.

    The other way around (where weakly referenced keys and strongly referenced values) is the WeakHashMap. When the garbage collection (GC) process discards a key, its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations.

    Just as an additional point, in my opinion, creating your own cache implementation is almost always a bad idea. Make use of libraries like google cache. https://www.tutorialspoint.com/guava/guava_caching_utilities.htm