MikeFHay
MikeFHay

Reputation: 9023

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.

Upvotes: 12

Views: 7599

Answers (5)

nanofarad
nanofarad

Reputation: 41281

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

Maps.synchronizedBiMap(yourHashBiMap);

Upvotes: 23

AllTooSir
AllTooSir

Reputation: 49402

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.

Upvotes: 2

T_01
T_01

Reputation: 1379

HashBiMap internally relies on HashMaps, which are not thread safe.

Upvotes: 0

gobernador
gobernador

Reputation: 5739

The implementation is based on two hash tables. The implementation of HashMap is based on one hash table, and HashMap is not synchronized. I think it is a good rule of thumb to assume that HashBiMap requires external synchronization.

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122008

As docs says

A BiMap backed by two hash tables.

And

HashMap is not synchronized.it must be synchronized externally. .

Upvotes: 0

Related Questions