• Post Reply Bookmark Topic Watch Topic
  • New Topic

ConcurrentHashMap  RSS feed

 
Ranch Hand
Posts: 193
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In ConcurrentHashMap there are 16 segments by default.At a time 16 threads can read/write concurrently

but what happens if more than 16 threads arrive at a time.Suppose 20 threads want to process on it. 16 threads work on different segments but 4 threads remain idle.

So beyond 16 threads a ConcurrentHashMap behaves like HashMap

How to overcome such situation ?
 
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do you mean by segments? Do you mean the default initial size of the map? This has nothing to do with how many threads can access it concurrently. As many threads can access the map concurrently as there are keys in the map, as long as each thread accesses a different key.

If two threads access the same key, one will have to wait until the other is done. This is NOT similar to HashMap.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ConcurrentHashMap allows concurrent access to the map. Part of the map called Segment (internal data structure) is only getting locked while adding or updating the map. So ConcurrentHashMap allows concurrent threads to read the value without locking at all. This data structure was introduced to improve performance. The allowed concurrency among update operations is guided by the optional concurrencyLevel constructor argument (default 16), which is used as a hint for internal sizing. The table is internally partitioned to try to permit the indicated number of concurrent updates without contention. Ideally, you should choose a value to accommodate as many threads as will ever concurrently modify the table. Using a significantly higher value than you need can waste space and time, and a significantly lower value can lead to thread contention.

Summary: Concurrenthashmap has segments and not threads. Each segment can be locked individually while other segments can be occupied by a different thread. So If there are 16 threads and let say each thread occupies different segment to do a write operation or all the threads want to write in a same segment then other threads would have to wait.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!