I have doubt understanding concurrenthashmap . If a section of conc hashmap is locked up by a writer thread then is it possible for a reader thread to read the same section of hashmap map simultaneously ? or does it need the lock to be released from the writer thread ?
Asked
Active
Viewed 531 times
-1
-
Are you asking about *using* a ConcurrentHashMap or about how it is *implemented*? – assylias Oct 30 '15 at 07:33
-
3Read the first two paragraphs of the [`ConcurrentHashMap` Javadoc](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html). Actually, read all of it. – Tomas Oct 30 '15 at 07:36
-
i read the concurrency level should not be too big as it might waste space and time. Please elaborate this . what is wrong if we have larger number of segments that can be locked what is the performance impact ? – jayendra bhatt Oct 30 '15 at 07:49
-
@jayendrabhatt This is a new question and should be posted as such. – Tomas Oct 30 '15 at 17:28
2 Answers
1
If you look at the source code of ConcurrentHashMap.get() then you can easily understand it.
No lock is required while reading from concurrent map but if the value is null
it checks again under readValueUnderLock
get(Object key, int hash) {
if (count != 0) { // read-volatile
HashEntry<K,V> e = getFirst(hash);
while (e != null) {
if (e.hash == hash && key.equals(e.key)) {
V v = e.value;
if (v != null)
return v;
return readValueUnderLock(e); // recheck
}
e = e.next;
}
}
return null;
}
readValueUnderLock(HashEntry<K,V> e) {
lock();
try {
return e.value;
} finally {
unlock();
}
}
Look at the ConcurrentHashMap.put() method as well that first calls lock()
and finally calls unlock()
put(K key, int hash, V value, boolean onlyIfAbsent) {
lock();
try {
...
} finally {
unlock();
}
}

Braj
- 46,415
- 5
- 60
- 76
0
No lock is required for reading.Locks are required to update the map.

Sainik Kumar Singhal
- 811
- 6
- 7