Why does exist WeakHashMap, but absent WeakSet?

JavaCollectionsGarbage CollectionWeak References

Java Problem Overview


From J. Bloch

> A ... source of memory leaks is > listeners > ... The best way to ensure that > callbacks are garbage collected > promptly is to store only weak > references to them, for instance, by > storing them only as keys in a > WeakHashMap.

So, why there isn't any WeakSet in the Java Collections framework?

Java Solutions


Solution 1 - Java

Collections.newSetFromMap

Set<Object> weakHashSet = 
    Collections.newSetFromMap(
        new WeakHashMap<Object, Boolean>()
    );

As seen in Collections.newSetFromMap documentation, passing a WeakHashMap to get a Set.

Solution 2 - Java

While you can indeed use Collections.newSetFromMap() to get a WeakSet, it's use cases are actually quite limited.

If you want to implement something like String.intern() you might want to have a look at Guava's Interners.newWeakInterner() functionality instead.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStan KurilinView Question on Stackoverflow
Solution 1 - JavamartView Answer on Stackoverflow
Solution 2 - JavaAxel DörflerView Answer on Stackoverflow