ConcurrentHashMap源码分析

妖狐艹你老母 2022-08-07 04:34 356阅读 0赞

简介

ConcurrentHashMap是HashMap更高效的线程安全版本的实现。不同于Hashtable简单的将所有方法标记为synchronized,它将内部数组分成多个Segment,每个Segment又是一个特殊的hash表,这样设计是为了减少锁粒度。另外它内部通过精巧的实现,让很多读操作(get(),size()等)甚至不需要上锁。

源码解析(基于jdk1.7.0_76)

Unsafe类的使用

下面是ConcurrentHashMap类的内部描述。介绍了Segment设计目的(锁分段)和Unsafe类的引入目的(实现volatile read和putOrderedObject延迟写):

  1. /*
  2. * The basic strategy is to subdivide the table among Segments,
  3. * each of which itself is a concurrently readable hash table. To
  4. * reduce footprint, all but one segments are constructed only
  5. * when first needed (see ensureSegment). To maintain visibility
  6. * in the presence of lazy construction, accesses to segments as
  7. * well as elements of segment's table must use volatile access,
  8. * which is done via Unsafe within methods segmentAt etc
  9. * below. These provide the functionality of AtomicReferenceArrays
  10. * but reduce the levels of indirection. Additionally,
  11. * volatile-writes of table elements and entry "next" fields
  12. * within locked operations use the cheaper "lazySet" forms of
  13. * writes (via putOrderedObject) because these writes are always
  14. * followed by lock releases that maintain sequential consistency
  15. * of table updates.
  16. */

ConcurrentHashMap使用了Unsafe类的4个方法来读/写segments[ ]和table[ ]数组,分别是

getObject() —普通读

getObjectVolatile() —volatile read

putOrderedObject() —有序写(延迟写)

compareAndSwapObject —CAS写,volatile write

  1. /**
  2. * Gets the jth element of given segment array (if nonnull) with
  3. * volatile element access semantics via Unsafe. (The null check
  4. * can trigger harmlessly only during deserialization.) Note:
  5. * because each element of segments array is set only once (using
  6. * fully ordered writes), some performance-sensitive methods rely
  7. * on this method only as a recheck upon null reads.
  8. */
  9. @SuppressWarnings("unchecked")
  10. static final <K,V> Segment<K,V> segmentAt(Segment<K,V>[] ss, int j) {
  11. long u = (j << SSHIFT) + SBASE;
  12. return ss == null ? null :
  13. (Segment<K,V>) UNSAFE.getObjectVolatile(ss, u);
  14. }
  15. /**
  16. * Gets the ith element of given table (if nonnull) with volatile
  17. * read semantics. Note: This is manually integrated into a few
  18. * performance-sensitive methods to reduce call overhead.
  19. */
  20. @SuppressWarnings("unchecked")
  21. static final <K,V> HashEntry<K,V> entryAt(HashEntry<K,V>[] tab, int i) {
  22. return (tab == null) ? null :
  23. (HashEntry<K,V>) UNSAFE.getObjectVolatile
  24. (tab, ((long)i << TSHIFT) + TBASE);
  25. }
  26. /**
  27. * Sets the ith element of given table, with volatile write
  28. * semantics. (See above about use of putOrderedObject.)
  29. */
  30. static final <K,V> void setEntryAt(HashEntry<K,V>[] tab, int i,
  31. HashEntry<K,V> e) {
  32. UNSAFE.putOrderedObject(tab, ((long)i << TSHIFT) + TBASE, e);
  33. }

UNSAFE类的putOrderedObject()是一个本地方法。它会设置obj对象中offset偏移地址对应的object型field的值为指定值。它是一个有序的、有延迟的putObjectVolatile()方法,并且不保证值的改变被其他线程立即看到。只有在field被volatile修饰(或者是数组)时,使用putOrderedObject()才有用(参见sun.misc.Unsafe源代码该方法描述)。而采用这种廉价的LazySet forms of write的原因,是因为它总是被放到了锁里面来调用的(如前面的ConcurrentHashMap描述所说),不用担心多线程写的顺序问题。

HashEntry定义

其中的setNext()分别被Segment.put/rehash/remove方法调用:

  1. /**
  2. * ConcurrentHashMap list entry. Note that this is never exported
  3. * out as a user-visible Map.Entry.
  4. */
  5. static final class HashEntry<K,V> {
  6. final int hash;
  7. final K key;
  8. volatile V value;
  9. volatile HashEntry<K,V> next;
  10. HashEntry(int hash, K key, V value, HashEntry<K,V> next) {
  11. this.hash = hash;
  12. this.key = key;
  13. this.value = value;
  14. this.next = next;
  15. }
  16. /**
  17. * Sets next field with volatile write semantics. (See above
  18. * about use of putOrderedObject.)
  19. */
  20. final void setNext(HashEntry<K,V> n) {
  21. UNSAFE.putOrderedObject(this, nextOffset, n);
  22. }
  23. // Unsafe mechanics
  24. static final sun.misc.Unsafe UNSAFE;
  25. static final long nextOffset;
  26. static {
  27. try {
  28. UNSAFE = sun.misc.Unsafe.getUnsafe();
  29. Class k = HashEntry.class;
  30. nextOffset = UNSAFE.objectFieldOffset
  31. (k.getDeclaredField("next"));
  32. } catch (Exception e) {
  33. throw new Error(e);
  34. }
  35. }
  36. }

Segment定义

Segment继承了ReentrantLock。它的结构其实就是一个Hash表。

注意Segment类中的count属性没有volatile描述。而对count属性的写操作均上了锁,读操作则使用了volatile read(见isEmpty/size方法)。

  1. /**
  2. * Segments are specialized versions of hash tables. This
  3. * subclasses from ReentrantLock opportunistically, just to
  4. * simplify some locking and avoid separate construction.
  5. */
  6. static final class Segment<K,V> extends ReentrantLock implements Serializable {
  7. /*
  8. * Segments maintain a table of entry lists that are always
  9. * kept in a consistent state, so can be read (via volatile
  10. * reads of segments and tables) without locking. This
  11. * requires replicating nodes when necessary during table
  12. * resizing, so the old lists can be traversed by readers
  13. * still using old version of table.
  14. *
  15. * This class defines only mutative methods requiring locking.
  16. * Except as noted, the methods of this class perform the
  17. * per-segment versions of ConcurrentHashMap methods. (Other
  18. * methods are integrated directly into ConcurrentHashMap
  19. * methods.) These mutative methods use a form of controlled
  20. * spinning on contention via methods scanAndLock and
  21. * scanAndLockForPut. These intersperse tryLocks with
  22. * traversals to locate nodes. The main benefit is to absorb
  23. * cache misses (which are very common for hash tables) while
  24. * obtaining locks so that traversal is faster once
  25. * acquired. We do not actually use the found nodes since they
  26. * must be re-acquired under lock anyway to ensure sequential
  27. * consistency of updates (and in any case may be undetectably
  28. * stale), but they will normally be much faster to re-locate.
  29. * Also, scanAndLockForPut speculatively creates a fresh node
  30. * to use in put if no node is found.
  31. */
  32. private static final long serialVersionUID = 2249069246763182397L;
  33. /**
  34. * The maximum number of times to tryLock in a prescan before
  35. * possibly blocking on acquire in preparation for a locked
  36. * segment operation. On multiprocessors, using a bounded
  37. * number of retries maintains cache acquired while locating
  38. * nodes.
  39. */
  40. static final int MAX_SCAN_RETRIES =
  41. Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
  42. /**
  43. * The per-segment table. Elements are accessed via
  44. * entryAt/setEntryAt providing volatile semantics.
  45. */
  46. transient volatile HashEntry<K,V>[] table;
  47. /**
  48. * The number of elements. Accessed only either within locks
  49. * or among other volatile reads that maintain visibility.
  50. */
  51. transient int count;
  52. /**
  53. * The total number of mutative operations in this segment.
  54. * Even though this may overflows 32 bits, it provides
  55. * sufficient accuracy for stability checks in CHM isEmpty()
  56. * and size() methods. Accessed only either within locks or
  57. * among other volatile reads that maintain visibility.
  58. */
  59. transient int modCount;
  60. /**
  61. * The table is rehashed when its size exceeds this threshold.
  62. * (The value of this field is always <tt>(int)(capacity *
  63. * loadFactor)</tt>.)
  64. */
  65. transient int threshold;
  66. /**
  67. * The load factor for the hash table. Even though this value
  68. * is same for all segments, it is replicated to avoid needing
  69. * links to outer object.
  70. * @serial
  71. */
  72. final float loadFactor;
  73. Segment(float lf, int threshold, HashEntry<K,V>[] tab) {
  74. this.loadFactor = lf;
  75. this.threshold = threshold;
  76. this.table = tab;
  77. }
  78. ......
  79. }

segments[]数组中的元素采用了延迟初始化,ConcurrentHashMap构造函数中只创建了segments[0],数组中其余元素全为null,而在ensureSegment()方法中才延迟创建Segment对象:

  1. public ConcurrentHashMap(int initialCapacity,
  2. float loadFactor, int concurrencyLevel) {
  3. ......
  4. // create segments and segments[0]
  5. Segment<K,V> s0 =
  6. new Segment<K,V>(loadFactor, (int)(cap * loadFactor),
  7. (HashEntry<K,V>[])new HashEntry[cap]);
  8. Segment<K,V>[] ss = (Segment<K,V>[])new Segment[ssize];
  9. UNSAFE.putOrderedObject(ss, SBASE, s0); // ordered write of segments[0]
  10. this.segments = ss;
  11. }

ensureSegment()方法功能同segmentAt(),只是增加了延迟初始化数组元素的功能:发现数组元素为null时,创建Segment对象并采用CAS操作放入数组内。

  1. /**
  2. * Returns the segment for the given index, creating it and
  3. * recording in segment table (via CAS) if not already present.
  4. *
  5. * @param k the index
  6. * @return the segment
  7. */
  8. @SuppressWarnings("unchecked")
  9. private Segment<K,V> ensureSegment(int k) {
  10. final Segment<K,V>[] ss = this.segments;
  11. long u = (k << SSHIFT) + SBASE; // raw offset
  12. Segment<K,V> seg;
  13. if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) {
  14. Segment<K,V> proto = ss[0]; // use segment 0 as prototype
  15. int cap = proto.table.length;
  16. float lf = proto.loadFactor;
  17. int threshold = (int)(cap * lf);
  18. HashEntry<K,V>[] tab = (HashEntry<K,V>[])new HashEntry[cap];
  19. if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
  20. == null) { // recheck
  21. Segment<K,V> s = new Segment<K,V>(lf, threshold, tab);
  22. while ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
  23. == null) {
  24. if (UNSAFE.compareAndSwapObject(ss, u, null, seg = s))
  25. break;
  26. }
  27. }
  28. }
  29. return seg;
  30. }

get()方法

内部使用了volatile read,遍历segments[ ]—>table[ ]—>HashEntry链表。在这个过程中,是没有显式用到锁的,仅仅是通过Unsafe类的volatile read,避免了阻塞,提高了性能:

  1. /**
  2. * Returns the value to which the specified key is mapped,
  3. * or {@code null} if this map contains no mapping for the key.
  4. *
  5. * <p>More formally, if this map contains a mapping from a key
  6. * {@code k} to a value {@code v} such that {@code key.equals(k)},
  7. * then this method returns {@code v}; otherwise it returns
  8. * {@code null}. (There can be at most one such mapping.)
  9. *
  10. * @throws NullPointerException if the specified key is null
  11. */
  12. public V get(Object key) {
  13. Segment<K,V> s; // manually integrate access methods to reduce overhead
  14. HashEntry<K,V>[] tab;
  15. int h = hash(key);
  16. long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
  17. if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
  18. (tab = s.table) != null) {
  19. for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
  20. (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
  21. e != null; e = e.next) {
  22. K k;
  23. if ((k = e.key) == key || (e.hash == h && key.equals(k)))
  24. return e.value;
  25. }
  26. }
  27. return null;
  28. }

isEmpty(),size()方法

为了避免上锁,该方法对Segment.modCount进行了2次检查:

  1. public boolean isEmpty() {
  2. /*
  3. * Sum per-segment modCounts to avoid mis-reporting when
  4. * elements are concurrently added and removed in one segment
  5. * while checking another, in which case the table was never
  6. * actually empty at any point. (The sum ensures accuracy up
  7. * through at least 1<<31 per-segment modifications before
  8. * recheck.) Methods size() and containsValue() use similar
  9. * constructions for stability checks.
  10. */
  11. long sum = 0L;
  12. final Segment<K,V>[] segments = this.segments;
  13. for (int j = 0; j < segments.length; ++j) {
  14. Segment<K,V> seg = segmentAt(segments, j);
  15. if (seg != null) {
  16. if (seg.count != 0)
  17. return false;
  18. sum += seg.modCount;
  19. }
  20. }
  21. if (sum != 0L) { // recheck unless no modifications
  22. for (int j = 0; j < segments.length; ++j) {
  23. Segment<K,V> seg = segmentAt(segments, j);
  24. if (seg != null) {
  25. if (seg.count != 0)
  26. return false;
  27. sum -= seg.modCount;
  28. }
  29. }
  30. if (sum != 0L)
  31. return false;
  32. }
  33. return true;
  34. }

为了避免上锁,该方法对Segment.modCount进行了2次检查,2次检查失败之后才上锁:

因为这些操作需要全局扫描整个table[ ],正常情况下需要先获得所有Segment实例的锁,然后做相应的查找、计算得到结果,再解锁,返回值。然而为了竟可能的减少锁对性能的影响,Doug Lea在这里并没有直接加锁,而是先尝试的遍历查找、计算2遍,如果两遍遍历过程中整个Map没有发生修改(即两次所有Segment实例中modCount值的和一致),则可以认为整个查找、计算过程中table[ ]没有发生改变,我们计算的结果是正确的,否则,在顺序的在所有Segment实例加锁,计算,解锁,然后返回。

  1. public int size() {
  2. // Try a few times to get accurate count. On failure due to
  3. // continuous async changes in table, resort to locking.
  4. final Segment<K,V>[] segments = this.segments;
  5. int size;
  6. boolean overflow; // true if size overflows 32 bits
  7. long sum; // sum of modCounts
  8. long last = 0L; // previous sum
  9. int retries = -1; // first iteration isn't retry
  10. try {
  11. for (;;) {
  12. if (retries++ == RETRIES_BEFORE_LOCK) { //RETRIES_BEFORE_LOCK = 2
  13. for (int j = 0; j < segments.length; ++j)
  14. ensureSegment(j).lock(); // force creation
  15. }
  16. sum = 0L;
  17. size = 0;
  18. overflow = false;
  19. for (int j = 0; j < segments.length; ++j) {
  20. Segment<K,V> seg = segmentAt(segments, j);
  21. if (seg != null) {
  22. sum += seg.modCount;
  23. int c = seg.count;
  24. if (c < 0 || (size += c) < 0)
  25. overflow = true;
  26. }
  27. }
  28. if (sum == last)
  29. break;
  30. last = sum;
  31. }
  32. } finally {
  33. if (retries > RETRIES_BEFORE_LOCK) {
  34. for (int j = 0; j < segments.length; ++j)
  35. segmentAt(segments, j).unlock();
  36. }
  37. }
  38. return overflow ? Integer.MAX_VALUE : size;
  39. }

Segment中的put()方法

put方法,主要通过scanAndLockForPut()获取锁。如果key已经存在,则更新HashEntry.value,否则创建新HashEntry,放入到链表头部。另外还会根据情况选择性的做rehash扩容。

  1. final V put(K key, int hash, V value, boolean onlyIfAbsent) {
  2. HashEntry<K,V> node = tryLock() ? null :
  3. scanAndLockForPut(key, hash, value);
  4. V oldValue;
  5. try {
  6. HashEntry<K,V>[] tab = table;
  7. int index = (tab.length - 1) & hash;
  8. HashEntry<K,V> first = entryAt(tab, index);
  9. for (HashEntry<K,V> e = first;;) {
  10. if (e != null) {
  11. K k;
  12. if ((k = e.key) == key ||
  13. (e.hash == hash && key.equals(k))) {
  14. oldValue = e.value;
  15. if (!onlyIfAbsent) {
  16. e.value = value;
  17. ++modCount;
  18. }
  19. break;
  20. }
  21. e = e.next;
  22. }
  23. else {
  24. if (node != null)
  25. node.setNext(first);
  26. else
  27. node = new HashEntry<K,V>(hash, key, value, first);
  28. int c = count + 1;
  29. if (c > threshold && tab.length < MAXIMUM_CAPACITY)
  30. rehash(node);
  31. else
  32. setEntryAt(tab, index, node);
  33. ++modCount;
  34. count = c;
  35. oldValue = null;
  36. break;
  37. }
  38. }
  39. } finally {
  40. unlock();
  41. }
  42. return oldValue;
  43. }

Segment中的scanAndLockForPut()和scanAndLock()方法

主要目的是获得锁,顺便进行了查找和创建工作(但不保证找到,可能获得了锁,但是查找工作还没结束)。

这里的while循环尝试自旋通过调用ReentrantLock.tryLock()获取锁,重试次数超限之后才会调用ReentrantLock.lock()。

  1. /**
  2. * Scans for a node containing given key while trying to
  3. * acquire lock, creating and returning one if not found. Upon
  4. * return, guarantees that lock is held. UNlike in most
  5. * methods, calls to method equals are not screened: Since
  6. * traversal speed doesn't matter, we might as well help warm
  7. * up the associated code and accesses as well.
  8. *
  9. * @return a new node if key not found, else null
  10. */
  11. private HashEntry<K,V> scanAndLockForPut(K key, int hash, V value) {
  12. HashEntry<K,V> first = entryForHash(this, hash);
  13. HashEntry<K,V> e = first;
  14. HashEntry<K,V> node = null;
  15. int retries = -1; // negative while locating node
  16. while (!tryLock()) {
  17. HashEntry<K,V> f; // to recheck first below
  18. if (retries < 0) {
  19. if (e == null) {
  20. if (node == null) // speculatively create node
  21. node = new HashEntry<K,V>(hash, key, value, null);
  22. retries = 0;
  23. }
  24. else if (key.equals(e.key))
  25. retries = 0;
  26. else
  27. e = e.next;
  28. }
  29. else if (++retries > MAX_SCAN_RETRIES) {
  30. lock();
  31. break;
  32. }
  33. else if ((retries & 1) == 0 &&
  34. (f = entryForHash(this, hash)) != first) {
  35. e = first = f; // re-traverse if entry changed
  36. retries = -1;
  37. }
  38. }
  39. return node;
  40. }

Segment中的scanAndLock()同scanAndLockForPut()方法类似,只是少了创建new HashEntry()的工作。其主要目的也是为了获取锁,只是不想空跑while循环,所以在循环中找点事情做—顺便遍历链表对key进行查找,如果发现数据不一致的情况,则重新循环:

  1. /**
  2. * Scans for a node containing the given key while trying to
  3. * acquire lock for a remove or replace operation. Upon
  4. * return, guarantees that lock is held. Note that we must
  5. * lock even if the key is not found, to ensure sequential
  6. * consistency of updates.
  7. */
  8. private void scanAndLock(Object key, int hash) {
  9. // similar to but simpler than scanAndLockForPut
  10. HashEntry<K,V> first = entryForHash(this, hash);
  11. HashEntry<K,V> e = first;
  12. int retries = -1;
  13. while (!tryLock()) {
  14. HashEntry<K,V> f;
  15. if (retries < 0) {
  16. if (e == null || key.equals(e.key))
  17. retries = 0;
  18. else
  19. e = e.next;
  20. }
  21. else if (++retries > MAX_SCAN_RETRIES) {
  22. lock();
  23. break;
  24. }
  25. else if ((retries & 1) == 0 &&
  26. (f = entryForHash(this, hash)) != first) { //发现数据不一致,则重置retries值
  27. e = first = f;
  28. retries = -1;
  29. }
  30. }
  31. }

Segment中的remove()方法

先entryAt方法定位数组位置,找到链表头,然后遍历链表,找到待删结点HashEntry后,直接修改待删结点pred结点的next指针(前面提到的HashEntry类中的setNext()方法)。另外Segment中的put()/rehash()也都采用了类似方式修改next指针。

  1. /**
  2. * Remove; match on key only if value null, else match both.
  3. */
  4. final V remove(Object key, int hash, Object value) {
  5. if (!tryLock())
  6. scanAndLock(key, hash);
  7. V oldValue = null;
  8. try {
  9. HashEntry<K,V>[] tab = table;
  10. int index = (tab.length - 1) & hash;
  11. HashEntry<K,V> e = entryAt(tab, index);
  12. HashEntry<K,V> pred = null;
  13. while (e != null) {
  14. K k;
  15. HashEntry<K,V> next = e.next;
  16. if ((k = e.key) == key ||
  17. (e.hash == hash && key.equals(k))) {
  18. V v = e.value;
  19. if (value == null || value == v || value.equals(v)) {
  20. if (pred == null)
  21. setEntryAt(tab, index, next);
  22. else
  23. pred.setNext(next);
  24. ++modCount;
  25. --count;
  26. oldValue = v;
  27. }
  28. break;
  29. }
  30. pred = e;
  31. e = next;
  32. }
  33. } finally {
  34. unlock();
  35. }
  36. return oldValue;
  37. }

Segment中的rehash()方法

注意,ConcurrentHashMap中的segments[]不会rehash,而只有Segment中的table[]会进行扩容。另外,rehash方法唯一被put方法所调用(所以rehash是在上锁的情况下的进行的)。

这里rehash扩容时有2个特别的地方:

1,对只有一个节点的链,直接将该节点赋值给新数组对应项即可。

2,对有多个节点的链,先遍历该链找到第一个后面所有节点的索引值不变的节点p,然后只重新创建节点p以前的节点即可,此时新节点链和旧节点链同时存在,在p节点相遇,这样即使有其他线程在当前链做遍历也能正常工作。

  1. /**
  2. * Doubles size of table and repacks entries, also adding the
  3. * given node to new table
  4. */
  5. @SuppressWarnings("unchecked")
  6. private void rehash(HashEntry<K,V> node) {
  7. /*
  8. * Reclassify nodes in each list to new table. Because we
  9. * are using power-of-two expansion, the elements from
  10. * each bin must either stay at same index, or move with a
  11. * power of two offset. We eliminate unnecessary node
  12. * creation by catching cases where old nodes can be
  13. * reused because their next fields won't change.
  14. * Statistically, at the default threshold, only about
  15. * one-sixth of them need cloning when a table
  16. * doubles. The nodes they replace will be garbage
  17. * collectable as soon as they are no longer referenced by
  18. * any reader thread that may be in the midst of
  19. * concurrently traversing table. Entry accesses use plain
  20. * array indexing because they are followed by volatile
  21. * table write.
  22. */
  23. HashEntry<K,V>[] oldTable = table;
  24. int oldCapacity = oldTable.length;
  25. int newCapacity = oldCapacity << 1;
  26. threshold = (int)(newCapacity * loadFactor);
  27. HashEntry<K,V>[] newTable =
  28. (HashEntry<K,V>[]) new HashEntry[newCapacity];
  29. int sizeMask = newCapacity - 1;
  30. for (int i = 0; i < oldCapacity ; i++) {
  31. HashEntry<K,V> e = oldTable[i];
  32. if (e != null) {
  33. HashEntry<K,V> next = e.next;
  34. int idx = e.hash & sizeMask;
  35. if (next == null) // Single node on list
  36. newTable[idx] = e;
  37. else { // Reuse consecutive sequence at same slot
  38. HashEntry<K,V> lastRun = e;
  39. int lastIdx = idx;
  40. for (HashEntry<K,V> last = next;
  41. last != null;
  42. last = last.next) {
  43. int k = last.hash & sizeMask;
  44. if (k != lastIdx) {
  45. lastIdx = k;
  46. lastRun = last;
  47. }
  48. }
  49. newTable[lastIdx] = lastRun;
  50. // Clone remaining nodes
  51. for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
  52. V v = p.value;
  53. int h = p.hash;
  54. int k = h & sizeMask;
  55. HashEntry<K,V> n = newTable[k];
  56. newTable[k] = new HashEntry<K,V>(h, p.key, v, n);
  57. }
  58. }
  59. }
  60. }
  61. int nodeIndex = node.hash & sizeMask; // add the new node
  62. node.setNext(newTable[nodeIndex]);
  63. newTable[nodeIndex] = node;
  64. table = newTable;
  65. }

参考资料

(1)JDK1.6

探索 ConcurrentHashMap 高并发性的实现机制

聊聊并发(四)——深入分析ConcurrentHashMap

特性描述:

  • 分离锁设计,降低锁竞争
  • 对写操作(put, remove, clear)的特别设计,减少读锁的使用
  • Segment对象属性volatile int count,volatile关键字保证多线程操作count的可见性

  • get方法中不上读锁,只有读到 value 域的值为null 时 , 读线程才需要加锁后重读(如读到value域为null,说明发生了重排序,需加锁后重读。而为何会为null,详细解析参见

    为什么ConcurrentHashMap是弱一致的

    )

  • 与HashMap不同的是,不允许Key和Value为null

ConcurrentHashMap 的高并发性主要来自于三个方面:
用分离锁实现多个线程间的更深层次的共享访问。
用 HashEntery 对象的不变性来降低执行读操作的线程在遍历链表期间对加锁的需求。
通过对同一个 Volatile 变量的写 / 读访问,协调不同线程间读 / 写操作的内存可见性。

(2)JDK1.7

ConcurrentHashMap源码分析整理

Java Core系列之ConcurrentHashMap实现(JDK 1.7)

Java多线程系列—“JUC集合”04之 ConcurrentHashMap

发表评论

表情:
评论列表 (有 0 条评论,356人围观)

还没有评论,来说两句吧...

相关阅读