None of the operations for any parallel collection need synchronization.
It is by design and in fact the collection lock does not affect other operations. (If they are not locked), in this case it will make them slower.
Is it possible that if 2 threads calls putIfAbsent () on an empty map with the same key that both can do their search to see that the key does not exist yet, so both threads then try to add it?
Both can try, but only one will succeed. It is impossible for two threads to succeed.
For some reason, when I first started using putIfAbsent (), I did not think that the call needed to be synchronized.
This is not true.
But now I donβt see how this can prevent both threads from adding their values ββif the time was right.
It performs the CAS operation in code, which means that only one operation can be successful, and the thread will know which one. The CAS operation does not require locking, because it uses a basic assembly instruction to execute it. In fact, you usually use locking using the CAS operation, and not vice versa.
source share