Normally (ie. not concurrently), putAll() cannot be more efficient than using lot’s of calls to put(), even assuming that you exclude the cost of building the other Map that you pass to putAll(). That’s because putAll() will need to iterate the passed Map’s elements, as well as running through the algorithm for adding each key value pair to the Map that put() executes.
But for a ConcurrentHashMap, does it make sense to construct a regular Map and then use putAll() to update it? Or should I just do 10 (or 100, or 1000) calls to put()?
Does the answer change for multiple calls to putIfAbsent()?
Thanks!
The first (mostly) threadsafe Map in Java Collections was the synchronized
HashMapusingCollections.synchronizedMap(). It worked by only allowing one operation at a time. Java 5 added theConcurrentHashMap, which works differently. Basically theMapis divided into slices. Aput()operation will only lock the relevant slice. It also added the threadsafe primitives likeputIfAbsent().The reason I explain this is that
putAll()might be more or less efficient depending on how it’s implemented. It may work by locking the whole map, which may actually be more efficient than trying to obtain individual locks on everyput(). Or it may work by doing a bunch ofput()calls anyway, in which case there’s not much difference.So if it makes sense for your code and you’re doing a lot of updates at once, I would use
putAll()unless it’sputIfAbsent()that you’re after.Edit: I just checked, the Java 6
ConcurrentHashMapimplementsputAll()as a loop ofput()operations so it’s no better or worse than doing this yourself.