Java WeakHashMap Example

WeakHashMap is a Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use.
Both null values and the null key are supported. This class has performance characteristics similar to those of the HashMap class and has the same efficiency parameters of initial capacity and load factor.

WeakHashMap Class Example

As we know that an entry in a WeakHashMap will automatically be removed when its key is no longer externally referenced and the key is due for garbage collection. In this example, we created two keys as key1 and key2 with values "ACTIVE" and "INACTIVE". Now make key1 as null and run the program. The output should be a single entry:
import java.util.Map;
import java.util.Map.Entry;
import java.util.WeakHashMap;

public class WeakHashMapExample {
    public static void main(final String[] args) {
        final Map<Key, Project> map = new WeakHashMap<>();
        Key key1 = new Key("ACTIVE");
        final Key key2 = new Key("INACTIVE");
        map.put(key1, new Project(100, "Customer Management System", "Customer Management System"));
        map.put(key2, new Project(200, "Employee Management System", "Employee Management System"));
 
        key1 = null;
        System.gc();
        for (final Entry<Key, Project> entry : map.entrySet()) {
            System.out.println(entry.getKey().getKey() + "   " + entry.getValue());
        }
    }
}

class Key {
    private String key;

    public Key(final String key) {
        super();
        this.key = key;
    }

    public String getKey() {
        return key;
    }

    public void setKey(final String key) {
        this.key = key;
    }
}
Output:
INACTIVE   [project id : 200, project name : Employee Management System, 
           project desc : Employee Management System ]
Note that the key1 is null and its entry is removed and garbage collected.

Reference

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments