Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 323
Blair Zajac Avatar asked Nov 17 '10 05:11

Blair Zajac


1 Answers

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.

like image 63
Laurence Gonsalves Avatar answered Sep 22 '22 04:09

Laurence Gonsalves