Guava MapMaker().weakKeys().makeMap() vs WeakHashMap
We have a Scala server that is getting a node tree using Protocol Buffers over a socket and we need to attach additional data to each node.
In a single threaded context and when both the node tree and the associated data will have their strong references rem开发者_JAVA技巧oved at the same time (due to going out of scope), is there any reason to use Google Guava's MapMaker with weakKeys() over using WeakHashMap? It seems that with MapMaker, one pays for synchronized access, which isn't needed in this case.
As an aside, it would be useful if MapMaker were to give access to the equivalence settings so one could choose reference equality but not care about weak or soft references.
One significant downside to WeakHashMap
is that it is not an "identity map". That is, it uses equals()
and hashCode
(rather than ==
and identityHashCode
) on keys, which really doesn't make sense for weak keys. You can work around this bug by making sure that your keys use identity equality in their equals
method.
精彩评论