java concurrent programming notes (x) - HashMap and ConcurrentHashMap

java concurrent programming notes (x) - HashMap and ConcurrentHashMap

HashMap parameters

There are two parameters that affect his performance

  • The initial capacity (the default is 16)
  • Load factor (default is 0.75)

Addressing HashMap

We need to insert a data or data we want to read, it will first hashMap key calculated according to a certain rule calculated hash value and the length of our array modulo, the number of tissue as a result of the insertion position index .

In the calculation, the cost is much higher than the cost of modulo displacement hashMap thus required length of the array must be n power of 2; in this case it will be key for the hash value of the (n-1) th power of 2 with operation, it is our results modulo operation is the same, hshMap initialization time, does not require the user must pass an integer of n-th power of 2, but according to the incoming value, calculate a satisfies 2 the capacity of the n-th power.

The reason hashMap insecurity

  • When hash carried resize, and prone to infinite loop

  • And fast-fail easily occurs when using iterator

    fast-fail :

    fail-fast mechanism java collection (Collection) of one error mechanism. When multiple threads operating on the same set of content, it may generate fail-fast event. For example: When a thread A iterator to traverse through a collection process, the content if the set is changed by the other thread; then thread A accesses the collection, an exception will be thrown ConcurrentModificationException generate fail-fast event.

ConcurrentHashMap

concurrentHashMap and HashMap difference is that the bottom of the outermost layer is not a big array, but an array of Segment, each Segment contains a similar array with hashMap the list. Segment inherited from ReetrentLock, it can easily Segment of the array is locked.

Segment: fragmentation

Guess you like

Origin www.cnblogs.com/xujie09/p/11706658.html