Based on the answers below :
It is Still not clear to me: What does the synchronized construct on the concurrentMap do, if anything. i.e. in the case of a concurrentmap, what is the difference if any between synchronized(map) versus non synchronizing. I am not interested in the correctness or believed goodness of the solution. Just an answer to the question:
Q:What is the difference between synchronizing on a concurrentmap and not synchronizing on the same? Specifically with regard to performance.. will suffice. Nothing more please.
I am only interested in what happens and no supplementary advice.
I have a theoretical question which I am having a bit of a mental problem resolving:
Assume I have a Concurrent Collection class say=>ConcurrentHashMap map;
Assume I have three methods:
method1: synchronized(map){
doSomethingWithThemap(); //Assume put integers 1.. 1000000
}
method2:doSomethingWithThemap(); //Note it is not synchronized
method3:doSomethingElseWithThemap(); //Assume put integers 2000000.. 3000000
Now assume 2 TestCases:
- TestCase1: Spawn two threads A & B. A calls method1 and B calls method3.
- TestCase2: Spawn two threads A’ & B’. A’ calls method2 and B’ calls method3.
From a performance point of view I would expect TestCase2 to win, since from what I understand, in TestCase1 B cannot add to the map, albeit concurrent, since the synchronized block will hold the lock on the map, and this is not the case in TestCase2.
My Unit Tests DO NOT validate this hypothesis.
Q: What am I missing here. i.e. Given a synchronized block on a concurrentcollection is performance impacted at all?
Your assumption that
ConcurrentHashMapinternally synchronizes on itself is not correct: according to the source code, the implementation usesjava.util.concurrent.locksobjects, instances of which are hidden inside the collection, so you cannot lock/synchronize on them.In general, this is a recommendation that writers of class libraries should follow: if you need to synchronize on an object, do not synchronize on
this; create a private object inside your class, and synchronize on that object instead. Otherwise, you may be facing concurrency issues caused by others synchronized on your object, and holding the lock indefinitely.