WeakHashMap Key Life Cycle
Store metadata beside objects with WeakHashMap: entries vanish once keys are garbage collected, so caches do not leak strong references.
Code
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
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.