Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is HashBiMap threadsafe?

The docs for com.google.common.collect.HashBiMap don't state whether it is thread-safe or not. I guess that means it isn't, but thought I'd ask in case I'm wrong.

like image 788
MikeFHay Avatar asked Jul 26 '13 15:07

MikeFHay


2 Answers

HashBiMap uses multiple custom hashtables internally, which are not thread safe. You should synchronize around accesses to HashBiMap with:

Maps.synchronizedBiMap(yourHashBiMap);
like image 194
nanofarad Avatar answered Oct 18 '22 02:10

nanofarad


Look at the source code, it doesn't seem synchronized to me .

private V More ...putInBothMaps(@Nullable K key, @Nullable V value, boolean force) {
   boolean containedKey = containsKey(key);
   if (containedKey && Objects.equal(value, get(key))) {
     return value;
   }
   if (force) {
     inverse().remove(value);
   } else {
     checkArgument(!containsValue(value), "value already present: %s", value);
   }
   V oldValue = delegate.put(key, value);
   updateInverseMap(key, containedKey, oldValue, value);
   return oldValue;
 }

Here delegate and inverseMap are the two Maps it uses internally.

like image 2
AllTooSir Avatar answered Oct 18 '22 02:10

AllTooSir