Java - The WeakHashMap Class

WeakHashMap is an implementation of the Map interface that stores only weak references to its keys. Storing only weak references allows a key-value pair to be garbage-collected when its key is no longer referenced outside of the WeakHashMap.
This class provides the easiest way to harness the power of weak references. It is useful for implementing "registry-like" data structures, where the utility of an entry vanishes when its key is no longer reachable by any thread.
The WeakHashMap functions identically to the HashMap with one very important exception: if the Java memory manager no longer has a strong reference to the object specified as a key, then the entry in the map will be removed.
Weak Reference − If the only references to an object are weak references, the garbage collector can reclaim the object's memory at any time.it doesn't have to wait until the system runs out of memory. Usually, it will be freed the next time the garbage collector runs.
Following is the list of constructors supported by the WeakHashMap class.
WeakHashMap()
This constructor constructs a new, empty WeakHashMap with the default initial capacity (16) and the default load factor (0.75).
WeakHashMap(int initialCapacity)
This constructor constructs a new, empty WeakHashMap with the given initial capacity and the default load factor, which is 0.75.
WeakHashMap(int initialCapacity, float loadFactor)

This constructor constructs a new, empty WeakHashMap with the given initial capacity and the given load factor.
WeakHashMap(Map t)
This constructor constructs a new WeakHashMap with the same mappings as the specified Map.
Apart from the methods inherited from its parent classes, TreeMap defines the following methods −
void clear()
Removes all mappings from this map.
boolean containsKey(Object key)
Returns true if this map contains a mapping for the specified key.
boolean containsValue(Object value)
Returns true if this map maps one or more keys to the specified value.
Set entrySet()
Returns a collection view of the mappings contained in this map.
Object get(Object key)
Returns the value to which the specified key is mapped in this weak hash map, or null if the map contains no mapping for this key.
boolean isEmpty()
Returns true if this map contains no key-value mappings.
Set keySet()
Returns a set view of the keys contained in this map.
Object put(Object key, Object value)
Associates the specified value with the specified key in this map.
void putAll(Map m)
Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map.
Object remove(Object key)
Removes the mapping for this key from this map if present.
int size()
Returns the number of key-value mappings in this map.
Collection values()
Returns a collection view of the values contained in this map.
The following program illustrates several of the methods supported by this collection −
import java.util.*;
public class WeakHashMap_Demo {

   private static Map map;
   public static void main (String args[]) {
      map = new WeakHashMap();
      map.put(new String("Maine"), "Augusta");
      
      Runnable runner = new Runnable() {
         public void run() {
            while (map.containsKey("Maine")) {
               try {
                  Thread.sleep(500);
               } catch (InterruptedException ignored) {
               }
               System.out.println("Thread waiting");
               System.gc();
            }
         }
      };
      Thread t = new Thread(runner);
      t.start();
      System.out.println("Main waiting");
      try {
         t.join();
      } catch (InterruptedException ignored) {
      }
   }
}
This will produce the following result −
Main waiting
Thread waiting

If you do not include the call to System.gc(), the system may never run the garbage collector as not much memory is used by the program. For a more active program, the call would be unnecessary.

    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page