WeakHashMap in Java

In the given tutorial, we will see the WeakHashMap class from the java.util package and the usage in Java.

  • WeakHashMap exclusively saves weak references into its keys. This the implementation class of the Map interface. When a key of a key-value pair is not referenced outside of the WeakHashMap, by keeping particularly weak references permits that pair for garbage collection.
  • WeakHashMap class gives a simple way to tackle the power of weak references. In the process of implementing “register like” data structures in which, the use of an entry fades away when its key is becomes unattainable by any thread, this class is appropriate for this process.
  • This class is like the HashMap only apart from the fact that in WeakHashMap, if an object is stated as key doesn’t have any references then it is qualified for garbage collection despite being associated with the WeakHashMap.

 

Constructors of the WeakHashMap :

  1. WeakHashMap() : It creates a new WeakHashMap and assigns 16 as its initial capacity and assigns 0.75 to its load factor (Because this are their default values).
  2. WeakHashMap(int initialCapacity) : It creates a new WeakHashMap and assigns the value given in the argument during constructor call, as its initial capacity and assigns 0.75 to its load factor.
  3. WeakHashMap(int initialCapacity, float loadFactor) : It creates a new WeakHashMap and assigns the values given in the argument during the constructor call, as its initial capacity and load factor respectively.
  4. WeakHashMap(Map t) : It creates a new WeakHashMap having the equivalent mappings of the stated Map.

Example :

Let’s see a program of this class :

package java;
import java.util.*;

class WHM_Demo
{
 public static void main(Sring args[]) throws Exception
 {
  WeakHashMap w= new WeakHashMap();
  Test t= new Test();

  //Entry to WeakHashMap
  w.put(t," Welcome ");

  System.out.println(w);

  t= null;

  //calling garbage collector
  System.gc();

  //Thread sleeps for 3 seconds
  THread.sleep(3000);

  System.out.println(w);
 }
}

class Test
{
 public void finalize()
 {
  System.ouy.println("Running finalize method");
 }
}

Output :

{main.java.Test@3125ee71= Welcome }
Running finalize method
{}

In the above program, we can see that how garbage collector dominates over WeakHashMap in Java programming.

Also read: Console reader() and writer() methods in Java with examples

Leave a Reply

Your email address will not be published. Required fields are marked *