Principle and the distinction between HashMap, Hashtable, ConcurrentHashMap

Principle and the distinction between HashMap, Hashtable, ConcurrentHashMap

HashTable

  • + Linked list to achieve the underlying array, whether key or value can not be null, thread-safe , thread-safe way to achieve lock the entire HashTable when data is modified, low efficiency, ConcurrentHashMap do the relevant optimization
  • The initial size of 11, expansion: newsize = oldsize * 2 + 1
  • The method of calculating the index: index = (hash & 0x7FFFFFFF)% tab.length

HashMap

  • + Linked list implementation of the underlying array, and the key may be stored null null values, thread-safe
  • The initial size of 16, expansion: newsize = oldsize * 2, size of certain n-th power of 2
  • Expansion for the entire Map, every time the expansion, the original elements in the array in order to recalculate the stowed position, and reinsert
  • Should the judge after the expansion element is inserted, there may not be valid expansion (if inserted expansion, if not insert it again, it will generate invalid expansion)
  • Map when the total number of elements exceeds 75% Entry array, triggering expansion operation, in order to reduce the length of the list, a more uniform distribution element
  • The method of calculating index: index = hash & (tab.length - 1)

ConcurrentHashMap

  • The bottom segment of the array using the linked list implementation +, thread-safe
  • Through the whole Map is divided into N Segment, we can provide the same thread-safe, but to enhance the efficiency of N times, 16 times the default upgrade. (Read operation does not lock because HashEntry the value of the variable is volatile, but also to ensure to read the latest value.)
  • Hashtable is synchronized for the entire Hash table, i.e., each exclusive thread to lock an entire table, allowing multiple modifications of ConcurrentHashMap concurrently, the key is the use of separation techniques Lock
  • Some methods require cross-sections, such as size () and containsValue (), they may need to lock the entire table and not just a segment, which requires in order to lock all segments After the operation, but also in order to release locks on all segments
  • Expansion: the expansion segment (the segment element segment corresponds to more than 75% of the length of the array Entry trigger expansion, the expansion will not be the entire the Map), prior to insertion detecting or need expansion, expansion effectively prevent invalid

Guess you like

Origin blog.csdn.net/m0_37587333/article/details/93736368