lelmarir
lelmarir

Reputation: 611

Java WeakHashMap leak when value references key

I have a WeakHashMap where the value may reference the key and this will cause a memory leak because the value is hold as Strong reference and thus the key will be Strongly reachable.

value references weak key

Is there a way to avoid this without changing the key or the value (I can only wrap them, but not modify their classes)

My ultimate goal is to keep the value from being collected by the GC until the key is strongly reachable. (and I need to access the value)

Upvotes: -1

Views: 76

Answers (2)

Andrey Smelik
Andrey Smelik

Reputation: 1266

As long as a value in a WeakHashMap has a reference to a key, the garbage collector will not be able to collect that key and there will be no memory leaks.

Upvotes: 0

Mureinik
Mureinik

Reputation: 312086

You could store a weak reference back to the key:

String myValue = "some value";
WeakHashMap<String, WeakReference<String>> myMap = new WeakHashMap<>();
myMap.put(myValue, new WeakReference<>(myValue));

Upvotes: 0

Related Questions