Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set equivalent of WeakHashMap?

Tags:

Is HashSet<WeakReference<T>> the Set equivalent of WeakHashMap<T>? That is, will entries be automatically deleted when they are no longer referenced?

If not, what is the equivalent?

like image 205
Barry Fruitman Avatar asked Oct 14 '13 19:10

Barry Fruitman


1 Answers

No, if an object referenced by one of the WeakReferences in the set gets garbage-collected, the WeakReference will still be included in the set and will not be removed automatically, but their referent will be null. A WeakHashMap uses additional code to remove the weakly referenced keys from the map when they're garbage-collected.

A set equivalent of a WeakHashMap is:

Set<T> set = Collections.newSetFromMap(new WeakHashMap<T, Boolean>());  

As a HashSet also uses a HashMap internally.

BTW: A WeakReference is just an object pointing to an object which may be garbage-collected despite the reference held by the WeakReference. The WeakReference itself will not be garbage-collected until it is not strongly referenced anywhere anymore just like all other objects.

like image 70
Njol Avatar answered Sep 19 '22 18:09

Njol