1.

How is WeakHashMap differs from other HashMap?

Answer»

WeakHashMap is using the WeakReference class, first, we need to understand how WeakReference works, WeakReference is a class which HOLDS the reference and GC captured that reference eagerly and does the garbage collection.

Below is the code snippet for WeakReference.

Integer prime = 1;  WeakReference<Integer> soft = new WeakReference<Integer>(prime); prime = NULL;

In this case, prime no gets garbage collected easily.

The WeakHashMap has utilized the WeakReference CLASSES, below code structure of WeakHashMap shows about the utilizing of WeakReference. The WeakHashMap extends the WeakReference classes

private static class ENTRY<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {         V value;         final int hash;         Entry<K,V> next;         /**          * Creates new entry.          */         Entry(Object key, V value,               ReferenceQueue<Object> queue,               int hash, Entry<K,V> next) {             super(key, queue);             this.value = value;             this.hash = hash;             this.next = next;         }         @SuppressWarnings("unchecked")         public K getKey() {             return (K) WeakHashMap.unmaskNull(get());         }

Key is stored as a WeakReference in ReferenceQueue, whenever the JVM get the key its add in the ReferenceQueue, so as soon as WeakHashMap check any key and if it found is deletes it from the table, this operation is called every time before any get operation.

Predominantly the WeakHashMap is given better memory performance, one can use this whenever we have to implement the custom cache or need to add a volume of the record in the Map.



Discussion

No Comment Found