Web / Apache Commons Collections Interview questions
How does ReferenceMap help prevent memory leaks in long-running caches?
A plain HashMap used as a cache holds a strong reference to every key and value it stores, which means nothing can ever be garbage collected until it's explicitly removed - if entries accumulate faster than they're evicted, the cache grows without bound and can eventually trigger an OutOfMemoryError.
ReferenceMap<String, byte[]> cache = new ReferenceMap<>(ReferenceStrength.HARD, ReferenceStrength.SOFT); cache.put("session-42", sessionPayload); // under memory pressure, the JVM's collector may reclaim the value // automatically; ReferenceMap notices and purges the stale entry
ReferenceMap lets you configure keys and/or values independently as HARD (a normal strong reference), SOFT (collected only when the JVM is under memory pressure), or WEAK (collected as soon as no other strong reference exists anywhere). Internally it registers those references with a ReferenceQueue, and on subsequent access it checks that queue and purges any entries whose reference has already been cleared by the collector.
This is a different guarantee than the JDK's WeakHashMap, which only lets keys be weakly referenced - ReferenceMap can apply reference semantics to values too, which matters most for caches where the large, memory-hungry object is the value (like a decoded image or a session payload) rather than the key used to look it up.
More Related questions...