Japer D.
Japer D.

Reputation: 774

Is "ConcurrentHashMap.putAll(...)" atomic?

Is the method ConcurrentHashMap.putAll(Map) supposed to be atomic?

I cannot find it in the documentation and it is not mentioned in the ConcurrentMap interface, so I guess the answer is no. I am asking it to be sure, since it wouldn't make sense if that operation wasn't atomic to be honest.

If it isn't atomic, what would be the best way to support atomic inserts of multiple items? Back to the good old synchronized?

Upvotes: 10

Views: 5245

Answers (4)

OlliP
OlliP

Reputation: 1595

To atomicize it, you'll have to use synchronized, yes

Not only that: you have to put a synchronized block around every public map method thus degrading concurrency.

Upvotes: 2

eboix
eboix

Reputation: 5131

putAll() is not atomic, but merely has the guarantee that each individual put() is atomic.

Upvotes: 2

ratchet freak
ratchet freak

Reputation: 48216

at the top of the doc

For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries.

Upvotes: 3

ruakh
ruakh

Reputation: 183446

It's not atomic, no. According to the class documentation:

For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries.

To atomicize it, you'll have to use synchronized, yes. There's no non-blocking way to do this.

Upvotes: 12

Related Questions