I need to associate some data with a key for its lifetime, so I am using a WeakHashMap
. However, in addition I need to get a key by its corresponding value. The easy way to do it is to hold on to the reference when creating a value:
public class Key {}
public class Value {
final public Key key;
public Value(Key k) {
key = k;
}
}
Of course, while I use Value
in my program, its key
won't go away. However, if there are no more references to either key or its value outside the map, will it be garbage collected? Or does the surviving strong reference in the value prevent it?