4

What is the need arises for introducing Weak HashMap when there is already other implementations available.

In short i have two issues :

  • Why jdk has WeakHashMap when there is HashMap and Concurrent HashMap in java ?

  • What is the use of it in real life applications ?

EDIT :

Though WeakHashmap key is a weak references but still they refer to something than on what basis GC discard keys in WeakHashMap.

Prateek
  • 12,014
  • 12
  • 60
  • 81
  • 1
    Docs on [WeakHashMap](http://docs.oracle.com/javase/7/docs/api/java/util/WeakHashMap.html) – Dennis Meng Aug 27 '13 at 17:43
  • its specifies what is HashMap not my questions :( – Prateek Aug 27 '13 at 17:43
  • 1
    I wasn't attempting to answer the question. The point of me posting that was more so that the *rest* of us would know what you were referring to. – Dennis Meng Aug 27 '13 at 17:44
  • possible duplicate of [When would you use a WeakHashMap or a WeakReference?](http://stackoverflow.com/questions/154724/when-would-you-use-a-weakhashmap-or-a-weakreference) – jmj Aug 27 '13 at 17:44
  • Please go read the doc : http://docs.oracle.com/javase/7/docs/api/java/util/WeakHashMap.html most of the answers are a part of it. – codeMan Aug 27 '13 at 17:46
  • @JigarJoshi i have gone through following question http://stackoverflow.com/questions/154724/when-would-you-use-a-weakhashmap-or-a-weakreference , http://stackoverflow.com/questions/5511279/what-is-a-weakhashmap-and-when-to-use-it but they were not implementing their need & practical use – Prateek Aug 27 '13 at 17:48
  • @codeMan After reading the docs my question arises of knowing its actual implementation and why its need arises to include in java – Prateek Aug 27 '13 at 17:49
  • @Prateek if you wanna see the implementation.. go ahead http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/WeakHashMap.java – codeMan Aug 27 '13 at 17:52
  • @codeMan Openjdk provides its source code not its use.Please help me out if u really have some use of it. – Prateek Aug 27 '13 at 18:03

6 Answers6

5

One Common use of WeakReferences and WeakHashMaps in particular is for adding properties to objects. Occasionally you want to add some functionality or data to an object but subclassing and/or composition are not an option in that case the obvious thing to do would be to create a hashmap linking the object you want to extend to the property you want to add. then whenever you need the property you can just look it up in the map. However, if the objects you are adding properties to tend to get destroyed and created a lot, you can end up with a lot of old objects in your map taking up a lot of memory

If you use a WeakHashMap instead the objects will leave your map as soon as they are no longer used by the rest of your program, which is the desired behavior.

The key of a WeakHashMap has weak reference. If the key has been garbage collected, then the entry in WeakHashMap object will automatically be deleted. It does not happen in normal HashMap. The entry will not be deleted if the key is garbage collected.

In the example I have taken one HashMap and one WeakHashMap. I will put entry in both the object and then later we will make the reference key as null and then garbage collected. And again check the entry. In the HashMap object entry will be there but in WeakHashMap object there will not be entry present.

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

public class WeakHashMapTest {
    public static void main(String[] args) {
        Map hashMap= new HashMap();

        Map weakHashMap = new WeakHashMap();

        String keyHashMap = new String("keyHashMap");
        String keyWeakHashMap = new String("keyWeakHashMap");

        hashMap.put(keyHashMap, "Ankita");
        weakHashMap.put(keyWeakHashMap, "Atul");
        System.gc();
        System.out.println("Before: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));

        keyHashMap = null;
        keyWeakHashMap = null;

        System.gc();  

        System.out.println("After: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));
    }
}

The output would be:

Before: hash map value:Ankita and weak hash map value:Atul
After: hash map value:Ankita and weak hash map value:null

More info:

Community
  • 1
  • 1
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • +1, also code reference: http://www.concretepage.com/java/example_weakhashmap.php – jmj Aug 27 '13 at 17:54
1

unlike the normal collections, which hold data until you decide to clear it out, data in WeakHashMap may be removed at any point in time and without notice when the JVM decides it wants the memory back. this makes it suitable for all sorts of caching purposes.

you can read up on weak references (and various other related types) here

radai
  • 23,949
  • 10
  • 71
  • 115
1

First you should understand the purpose of WeakReferences. Once you understand that then reading the WeakedHashMap definition from docs clearly tells its purpose

A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

You can use an object as a key without preventing its collection.

From the WeakHashMap documentation:

When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
0

They provide a a way of using an object as a key without creating a strong reference to it. This is good practice where you don't want to hinder JVM's ability to garbage collect the object but yet still want the ability to track some aspect of the object. This makes them ideal for caching or storing metadata about the object.

Derek Meyer
  • 497
  • 7
  • 22
0

From the answers, the only cache feature is automatic eviction on GC and it probably won't happen during young gen GC but in tenured old gen GC for the usecase of caching large files that are used for sometime. Is the entry evicted on any GC or only when tenured generation is full?

Besides unpredictable eviction there is no size constraint that can be specified on the map, so any cache library with pre-defined cache size (number of elements and memory size) along with an eviction strategy seems like a better option to me as most caches also include a provision to reduce size/flush more elements when heap usage goes beyond a certain size. These also provide consistency during concurrency.

So, I wonder if there is a good use case to use this besides the risk of memory leaks and missed hits due to bad design.

kisna
  • 2,869
  • 1
  • 25
  • 30