Java WeakHashMap Example

Published May 16, 2022

The WeakHashMap interface is based on a Hash table, with weak keys. The entries in this class interface are automatically removed when their keys are no longer in use.

The performance characteristics of this class are similar to those of HashMap and its initial capacity and load factor are also the same.

As with most collection classes, WeakHashMap is non-synchronized. However, it can be constructed using a Collections.synchronized map.

 

Example

import java.util.HashMap;

import java.util.Map;

import java.util.WeakHashMap;

public class WeakHashMap_Example {

            private static Map map;

              public static void main (String args[]) {

                  map = new WeakHashMap();

                  map.put(new String("First"), "Second");

                  Runnable runner = new Runnable() {

                    public void run() {

                        while (map.containsKey("First")) {

                          try {

                              Thread.sleep(500);

                          } catch (InterruptedException ignored) {

                          }

                          System.out.println("HashMaps");

                          System.gc();

                        }

                    }

                  };

                  Thread t = new Thread(runner);

                  t.start();

                  System.out.println("Our WeakHashmaps");

                  try {

                    t.join();

                  } catch (InterruptedException ignored) {

                  }

              }

}

 

Output:

Our WeakHashmaps

HashMaps

 

Keywords: Java WeakHashMap , Java Collections, Java

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

87 Views