How to cache with weak references when values refe

2019-02-24 23:30发布

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 SoftReferences 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.

4条回答
一纸荒年 Trace。
2楼-- · 2019-02-24 23:52

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.

查看更多
做自己的国王
3楼-- · 2019-02-25 00:00

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

Value v = SomeLibrary.giveMeSomething();
String k = v.getName();
String k1 = new String(k);
cache.put(k1,v);

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?

查看更多
唯我独甜
4楼-- · 2019-02-25 00:04

Unfortunately, this is unsolvable without ephemerons.

查看更多
够拽才男人
5楼-- · 2019-02-25 00:08

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.

查看更多
登录 后发表回答