3

I am new to Java and stackoverflow and am seeking answer from experienced folks, who have worked on Collections Framework.

I read that hashTable is thread safe and so is concurrentHashMap, but a concurrentHashMap is faster than a hashTable, since it gives lock on segments of the map to the accessing threads.

How does this work internally? How is the size of segment decided? Example: if there are 40 entries in concurrentHashMap, and 3 threads trying to retrieve/modify data, how will the segments be decided?

Any images/explanations/code on this would be really awesome. Thanks in advance.

Karan
  • 2,120
  • 15
  • 27
  • basically ConcurrentHashMap have better performance because implemented using CAS operations instead of locking which causes many context switches and waits. – Maxim Dec 22 '14 at 22:02
  • This is an excellent article on ConcurrentHashMap: http://www.burnison.ca/articles/the-concurrency-of-concurrenthashmap – Matt Coubrough Dec 22 '14 at 22:02
  • Thank you, this really helps. Not sure why it is marked duplicate since the other question is "Difference between HashMap and HashTable" – Karan Dec 29 '14 at 07:53

1 Answers1

-2

concurrentHashMap - Lock free algorithm. There is no synchronization between read or write operation. As per java Doc

A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.

HashTable - Everything is synchronized. Its completely synchronized between read and write operation

Siva Kumar
  • 1,983
  • 3
  • 14
  • 26
  • Thanks Siva. "retrieval operations do not entail locking" it means write operations do lock segments? " there is not any support for locking the entire table in a way that prevents all access" this line suggests that some parts are locked but not entire table. Could you explain if any locks are gained by thread on table/segments at any point? – Karan Dec 22 '14 at 18:01
  • 2
    `ConcurrentHashMap` is *not* lock-free. – Steven Schlansker Dec 22 '14 at 19:31
  • Steven is right, CHM is certainly ***not*** lock-free. ConcurrentLinkedQueue is lock-free but the CHM uses segemented locks. – John Vint Dec 22 '14 at 22:17