Faster Synchronization Through Hash Maps

May 17, 2013

As part of a load testing project, I needed to collect and store data as fast as possible in a multi-threaded environment. This meant synchronizing on collections to avoid collisions. Synchronization is always a bad idea in any performance critical application. In my simple testing, adding to a synchronized ArrayList can be almost 4x slower than a non-synchronized ArrayList. Then, I had an interesting idea of what would be faster: a synchronized list or a hash map keyed off the local thread id? In my testing, the map was actually faster as it required no synchronization…almost 2x faster. It is still slower than non-synchronized list, understandably so, but it at least gets to within 2x worse. The hash map example works since upon retrieval, you are guaranteed that the list being added to cannot collide except with itself as the list is tied to a specific thread. This is similar to a ThreadLocal, except ThreadLocal is even slower performance. The downfall of this method is that it assumes you are primarily concerned with ‘add’ and that reads only occur at the end at which point you have to merge. This also assumes that order does not matter. In my load testing project, all of that holds true. All I care about is storing metrics as fast as possible without colliding.

Comments are closed.