Java WeakHashMap Example

What is WeakHashMap?

java.util.HashMap has strong key reference, even if the key is garbage collected also we can use the entry in the HashMap. But in the case of java.util.WeakHashMap key reference is very weak as its name says. Here is one simple example to store values in both HashMap and WeakHashMap and making key as null.. see the results.

Example

package com.vinod.collections;
import java.util.*;
public class WeakHashMapExample {
    public static void main(String[] args) {
        Map<String, String> hashMap = new HashMap<String, String>();
        String nameKey = new String("name");
        hashMap.put(nameKey, "Santhosh");
        System.gc();
        System.out.println("Hashmap after creation        :" + hashMap.get("name"));
        nameKey = null;
        System.gc();
        System.out.println("Hashmap after key is null     :" + hashMap.get("name"));
        Map<String, String> weakHashMap = new WeakHashMap<String, String>();
        String weaknameKey = new String("name");
        weakHashMap.put(weaknameKey, "Santhosh");
        System.gc();
        System.out.println("WeakHashMap after creation    :"
                + weakHashMap.get("name"));
        weaknameKey = null;
        System.gc();
        System.out.println("WeakHashMap after key is null :"
                + weakHashMap.get("name"));
    }
}
 

Output

Hashmap after creation        :Santhosh

Hashmap after key is null     :Santhosh

WeakHashMap after creation    :Santhosh

WeakHashMap after key is null :null

No comments:

Post a Comment

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts