0

i was going through concurrent hash map , as per my knowledge at this point , they are by default segmented into 16 parts. each part have its own share of key value pairs. If a thread want to hold a lock on a key value pair it will lock that entire segment. (Please correct me if i am wrong anywhere). Now in this link it is mentioned as chm is good when writers are less . i was wondering if we increase the number of segments , i mean making it comparable to number key value pairs , isnt it possible to create concurrency for large number of writer threads operating on the same CHM . Also, how costly will it be as far as memory consumption is concerned due to locks present in the CHM.

Thanks

Jayendra

jayendra bhatt
  • 1,337
  • 2
  • 19
  • 41

1 Answers1

3

If I understand your question correctly, it is answered just right in the JavaDoc:

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. Because placement in hash tables is essentially random, the actual concurrency will vary. 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. But overestimates and underestimates within an order of magnitude do not usually have much noticeable impact. A value of one is appropriate when it is known that only one thread will modify and all others will only read. Also, resizing this or any other kind of hash table is a relatively slow operation, so, when possible, it is a good idea to provide estimates of expected table sizes in constructors.

kan
  • 28,279
  • 7
  • 71
  • 101
  • So according to it there will be a performance impact if the hashtable undergo a resize. but if i provide a large concurrency level value in the constructor itself then will there be any issue while working with large number of modifier threads, also please let me know whether the size of all segments are equal or variable( i believe they are variable ) . – jayendra bhatt Mar 02 '15 at 05:57
  • @jayendrabhatt Yes, I believe this kind of optimisation could be only driven by profiling of your application. If I understand it correctly, segments are populated based on hashcode. So if hashcode of your objects is _good_, the size of segments will be nearly the same. – kan Mar 02 '15 at 08:25
  • 1
    @jayendrabhatt _good_ as it is good for hashing in common sense, so your objects give codes which are evenly distributed. http://stackoverflow.com/questions/16629893/good-hashcode-implementation – kan Mar 02 '15 at 21:37