WeakHashMap Key Life Cycle

Store metadata beside objects with WeakHashMap: entries vanish once keys are garbage collected, so caches do not leak strong references.

JavaResilience

Code

snippet
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

public class Attachments {

    public static void main(String[] args) throws InterruptedException {
        Map<Object, String> weak = new WeakHashMap<>();
        Map<Object, String> strong = new HashMap<>();

        Object session = new Object();
        weak.put(session, "metadata");
        strong.put(session, "metadata");

        System.out.println("before: weak=" + weak.size() + " strong=" + strong.size());

        // 释放强引用并请求 GC:WeakHashMap 的键只被弱引用持有
        session = null;
        System.gc();
        Thread.sleep(100); // 给 GC 一点时间,行为不作保证

        System.out.println("after : weak=" + weak.size() + " strong=" + strong.size());
        System.out.println("strong still holds value: " + strong.containsValue("metadata"));
    }
}

Inside the snippet

Count the class Attachments as the entire surface area of WeakHashMap Key Life Cycle.

Putting it to use

Running the file prints labeled results such as before: weak=, after : weak=, strong still holds value: — each operation’s effect is visible in the output.

Core lines

Thread.sleep(100); // 给 GC 一点时间,行为不作保证
System.out.println("after : weak=" + weak.size() + " strong=" + strong.size());

Interactive Tools for This Topic

FAQ

What does WeakHashMap Key Life Cycle print when run?
Run it as a complete program — the output lines carry labels such as `before: weak=`, `after : weak=`, `strong still holds value:`.