Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

As of Guava 10, MapMaker.softKeys is deprecated, and the corresponding method doesn't exist in CacheBuilder.

Why was this change made? What do I need to do with existing code that use it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
97 views
Welcome To Ask or Share your Answers For Others

1 Answer

I wrote the question because, initially, I did genuinely wonder why (as I had existing code that used softKeys). However, the reason was obvious on reflection and I decided to post it here, in case someone else also uses softKeys and was wondering the same thing.

In short, the reason was that softKeys never made any sense in the first place. Thus, its initial inclusion was in itself a mistake, one which the Guava developers are rectifying via deprecation.

In general, you use soft references if you want the object to stick around for a little after all the strong references are gone; in contrast, with weak references, the object usually gets collected soon once there are no strong or soft references left. This is useful for cached values that you want to hold on to temporarily, so that a lookup using the corresponding key will "revive" a strong reference for the value.

However, this behaviour doesn't make any sense for keys:

  • Since softKeys and weakKeys maps use an identity-based lookup, the only way to get at an entry of interest is to posess a strong reference to its key.? Thus, once there are no strong key references left, the entry is effectively dead (with no possibility of revival).
  • The only practical difference between softKeys and weakKeys is how long an entry remains in the map after all the strong references to its key are gone. Since such entries are dead anyway, using softKeys instead of weakKeys only delays the entry's eviction, for no good reason.

Thus, most times when coming across code that uses softKeys, a much more suitable replacement is weakKeys.

? I am not considering the case of fetching the entry via iteration, or anything other than key-based lookup, since maps are primarily about key-based operations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...