☕ Java Intermediate

What is WeakReference and WeakHashMap in Java?

Answer

A WeakReference holds a reference to an object that does not prevent the object from being garbage collected. When only weak references point to an object, the GC is free to collect it. Useful for memory-sensitive caches — if memory is low, the cache entries are collected automatically. WeakHashMap is a Map implementation where keys are held with weak references. When a key is no longer referenced elsewhere in the program, the entry is automatically removed from the map. This makes WeakHashMap ideal for caches and canonicalized mappings (like the String pool concept) where you want the map entry to disappear when the key object is no longer used elsewhere in the application.