Search code examples
javasynchronizationapache-commonsbidirectional

BidiMap Synchronization


When using the apache commonds bidimap, how do you handle synchronization. For example, if I create the map as shown below

BidiMap oneWay = new DualHashBidiMap();
BidiMap theOtherWay = oneWay.inverseBidiMap();

So if I am going to add/access/remove a key/value pair to one of the above variables, to I need to synchronize both (thread synchronization). Seems like I am not gaining anything over implementing this functionality with 2 maps if I need to do this.

Thanks for you time in looking at this problem.


Solution

  • By synchronization, are you referring to accessing the two from different threads or are you thinking that if you add a key/value pair to the inverse map you would need to add it to the forward map as well? If it's the latter, you don't have to do that. The inverse map is a view of the forward map, so changing one will always affect the other as well.

    If you're asking about thread synchronization... well, I'm not sure what commons collections provides for that. My recommendation would be to use Guava and its BiMap interface instead of apache commons. In addition to using generics, Guava has a Maps.synchronizedBiMap(BiMap) method that creates a synchronized wrapper.