I'm using Guava's Cache<Key, Value>
. Whenever Key
is no more strongly reachable, the cache entry should be garbage collected (someday...). Using CacheBuilder.weakKeys()
would do exactly that, if there weren't a reference from Value
back to Key
.
I could make this reference weak, but this could anytime make my Value
quite invalid. I could handle it, but I'd prefer not to.
I could use weakValues()
, but this could lead to very early evictions, as my values are only referenced for a short time.
Maybe I could use softValues()
, but SoftReference
s are quite broken.
Probably I'm getting something wrongly.... what is the right solution?
Update
What I need could be achieved simply by putting a reference to Value
into each Key
, but this is not possible as Key
is not under my control. If it was, then I'd need no cache, no weak references, nothing.
This way, each Key
would keep its corresponding Value
reachable, which is fine1. Also each Value
would keep its Key
reachable, but this is no problem as there're no long existing references to Value
.
1 Some expiration would be better but it's not necessary.
The pointer from Value -> Key doesn't matter as long as nothing else is holding on to Value.
When the Cache dumps Key, it will be collected.
If you have System->Cache->Key<-Value, when Cache drops key you get System->Cache Key<-Value. The link from Key back up to System (the memory root for this example) is broken, and Key will be recovered.
Do you think it might be possible to create a copy of key, and use that as the key in the map? I am thinking you might have something like
This will work b/c k.equals(k1) and k != k1. Hopefully you can create a copy or clone of the type used for Key (which probably isn't String in your case).
However, this changes the lifecycle of the key -- since it is no longer the one in Value. If you have control over the lifecycle of the particular object you've put in the map, then you're OK.
Do you think that might work?
Unfortunately, this is unsolvable without ephemerons.
If you really want weakKeys, then having a weak reference from the value to the key is the right thing to do.
If that doesn't feel right to you, then please provide more info about what you're trying to accomplish.