3

This question was recently asked to me in java interview. I tried to search it later but couldn't find the exact answer. In case if any1 have a link o the answer please let me know. So here goes my question :

ConcurrentHashMap and Hashtable are synchronized. But which locking mechanism it uses during write operation while locking.

NoNaMe
  • 6,020
  • 30
  • 82
  • 110
sussie
  • 33
  • 1
  • 3
  • 1
    It is explained in the Javadoc class comment of these classes. – wero Sep 19 '15 at 11:50
  • Hope it will help : [concurrenthashmap and hashtable][1] [1]: http://stackoverflow.com/questions/12646404/concurrenthashmap-and-hashtable-in-java – Rahman Sep 19 '15 at 11:51

3 Answers3

3

The great thing about open source is you can just look up the source code! This bit is particularly relevant.

The concurrency in ConcurrentHashMap is quite intricate - it breaks the contents up into Segments to avoid locking the whole table, and uses volatile fields to allow lock-free concurrent reads.

hugh
  • 2,237
  • 1
  • 12
  • 25
1

ConcurrentHashMap uses internally divides buckets into segments and one particular segment can be locked by a thread for writing purpose.

Segment is nothing but a static class which is specialized version of hash tables and implements Reentrantlock to simplify locking as

static class Segment<K,V> extends ReentrantLock implements Serializable {
        private static final long serialVersionUID = 2249069246763182397L;
        final float loadFactor;
        Segment(float lf) { this.loadFactor = lf; }
}

Segments's constructor calls ReentrantLock's no arg constructor and creates a non fair lock.

Vaibhav Jain
  • 1,939
  • 26
  • 36
0

Two main features of ConcurrentHashMap is:

  • While writing on ConcurrentHashMap, locks only a part of the map
  • Reads can generally happened without locking.

its possible to have two parallel threads writing to the ConcurrentHashMap at the same time. As per the default implementation of ConcurrentHashMap, atmost 16 threads can write & read in parallel. But the worst case is, if the two objects lie in the same segment or partition of ConcurrentHashMap, then parallel write would not be possible.

soorapadman
  • 4,451
  • 7
  • 35
  • 47