Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

WeakHashMap: put, get, containsKey, containsValue, and size

Learn how five WeakHashMap operations behave in Java SE 21 when keys are weak, values are strong, and null can mean more than one thing.

Version: Java SE 21

Syntax

java.util.WeakHashMap<K, V> (Java SE 21)
public V put(K key, V value)
public V get(Object key)
public boolean containsKey(Object key)
public boolean containsValue(Object value)
public int size()

WeakHashMap.put/get/containsKey/containsValue/size are five operations on java.util.WeakHashMap<K, V>. The map holds non-null keys weakly and values strongly. Once a key object becomes weakly reachable, the garbage collector (GC) can clear its weak reference, and the map can then discard the entry. There is no guaranteed deadline. A strong path from a value back to its own key, direct or indirect, can prevent this.

Key lookup uses hashCode() and equals(), not just object identity (==). A distinct but equal object can find an entry, but does not by itself keep the stored key object alive. The map accepts one null key and allows null values.

put(K key, V value) adds a mapping or replaces the value for an equal key. It returns the previous value, or null if there was no mapping or the previous value was null. get(Object key) returns the current value, with null meaning either an absent mapping or a mapped null. containsKey(Object key) tests for a mapping regardless of its value and distinguishes those cases. Two calls are not a single atomic observation.

containsValue(Object value) tests whether at least one mapping has an equal value, including null when you search for it. size() counts mappings, including those with a null value, at the time of the call. Results can change without an application write as the map removes entries after GC clears their key references.

The map has neither TTL (time-based expiry) nor LRU (least-recently-used eviction). It is not thread-safe: Collections.synchronizedMap(...) can synchronize shared access, but synchronization does not stop GC-related cleanup.

Examples

import java.lang.ref.Reference;
import java.util.WeakHashMap;

public class WeakHashMapDemo {
    record Key(int id) {}

    public static void main(String[] args) {
        var map = new WeakHashMap<Key, String>();
        var stored = new Key(1);
        var equal = new Key(1);
        var missing = new Key(2);

        System.out.println("first put: " + map.put(stored, "draft"));
        System.out.println("replacement put: " + map.put(equal, "ready"));
        map.put(null, null);

        System.out.println("get(equal): " + map.get(equal));
        System.out.println("get(null): " + map.get(null));
        System.out.println("get(missing): " + map.get(missing));
        System.out.println("containsKey(null): " + map.containsKey(null));
        System.out.println("containsKey(missing): " + map.containsKey(missing));
        System.out.println("containsValue(null): " + map.containsValue(null));
        System.out.println("size: " + map.size());

        Reference.reachabilityFence(stored);
        Reference.reachabilityFence(equal);
    }
}

Result

first put: null
replacement put: draft
get(equal): ready
get(null): null
get(missing): null
containsKey(null): true
containsKey(missing): false
containsValue(null): true
size: 2

`equal` is distinct from but equal to `stored`: it replaces `draft` with `ready` without adding a mapping. `get` returns `null` for both the `null` key and `missing`, but only the former is present. `Reference.reachabilityFence` keeps both key objects strongly reachable through the last print; the example does not test GC timing.

Related lessons

  • Java · Lesson 18 · Advanced · Version: 2

Sources