本文转自以下连接,因为原文的排版不是很清晰,这里进行了从新排版以及部分修改:java
Map 这样的 Key Value 在软件开发中是很是经典的结构,经常使用于在内存中存放数据。面试
本篇主要想讨论 ConcurrentHashMap 这样一个并发容器,在正式开始以前我以为有必要谈谈 HashMap,没有它就不会有后面的 ConcurrentHashMap。bootstrap
众所周知 HashMap 底层是基于 数组 + 链表 组成的,不过在 jdk1.7 和 1.8 中具体实现稍有不一样。在 1.7 中HashMap的数据结构图以下:数组
咱们先来看看 1.7 中HashMap的实现,源码以下:安全
这是 HashMap 中比较核心的几个成员变量;看看分别是什么意思?数据结构
这里重点解释一下负载因子,HashMap中共有四个构造函数,咱们来看一下HashMap中较为重要的两个构造函数,源码以下:多线程
public HashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); } public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; threshold = initialCapacity; init(); }
因为给定的 HashMap 的容量大小是固定的,而从源码中能够看到默认初始化时给定的默认容量为 16,负载因子为 0.75。Map 在使用过程当中不断的往里面存放数据,当数量达到了 16 * 0.75 = 12
就须要将当前 16 的容量进行扩容,而扩容这个过程涉及到 rehash、复制数据等操做,因此很是消耗性能。并发
所以一般建议能提早预估 HashMap 的大小最好,尽可能的减小扩容带来的性能损耗。根据代码能够看到其实真正存放数据的数组是:app
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
那么这个数组,它又是如何定义的呢?以下:
Entry 是 HashMap 中的一个内部类,从他的成员变量很容易看出:
知晓了基本结构后,那咱们来看看其中最为重要的写入以及获取函数。
一、put 方法:
public V put(K key, V value) { if (table == EMPTY_TABLE) { inflateTable(threshold); } if (key == null) return putForNullKey(value); int hash = hash(key); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; }
源码说明:
二、addEntry与createEntry方法:
void addEntry(int hash, K key, V value, int bucketIndex) { if ((size >= threshold) && (null != table[bucketIndex])) { resize(2 * table.length); hash = (null != key) ? hash(key) : 0; bucketIndex = indexFor(hash, table.length); } createEntry(hash, key, value, bucketIndex); } void createEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<>(hash, key, value, e); size++; }
源码说明:
三、get 方法:
再来看看 get 方法,以及该方法内调用的 getEntry 方法:
public V get(Object key) { if (key == null) return getForNullKey(); Entry<K,V> entry = getEntry(key); return null == entry ? null : entry.getValue(); } final Entry<K,V> getEntry(Object key) { if (size == 0) { return null; } int hash = (key == null) ? 0 : hash(key); for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } return null; }
源码说明:
不知道从 1.7 的实现你们看出须要优化的点没有?其实一个很明显须要优化的地方就是:
当 Hash 冲突严重时,在桶上造成的链表会变的愈来愈长,这样在查询时的效率就会愈来愈低;时间复杂度为 O(N)。
所以在 1.8 中重点优化了这个查询效率。在 1.8 中 HashMap 的结构图:
咱们先来看看在1.8中HashMap几个核心的成员变量:
/** * The default initial capacity - MUST be a power of two. */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The bin count threshold for using a tree rather than list for a * bin. Bins are converted to trees when adding an element to a * bin with at least this many nodes. The value must be greater * than 2 and should be at least 8 to mesh with assumptions in * tree removal about conversion back to plain bins upon * shrinkage. */ static final int TREEIFY_THRESHOLD = 8; /** * The table, initialized on first use, and resized as * necessary. When allocated, length is always a power of two. * (We also tolerate length zero in some operations to allow * bootstrapping mechanics that are currently not needed.) */ transient Node<K,V>[] table; /** * Holds cached entrySet(). Note that AbstractMap fields are used * for keySet() and values(). */ transient Set<Map.Entry<K,V>> entrySet; /** * The number of key-value mappings contained in this map. */ transient int size;
能够看到,和 1.7 大致上都差很少,仍是有几个重要的区别:
Node 的核心组成其实也是和 1.7 中的 HashEntry 同样,存放的都是 key value hashcode next 等数据。
而后咱们再来看看核心方法。
一、put 方法(put里调用的是putVal):
看似要比 1.7 的复杂,咱们一步步进行拆解:
二、get 方法(get 里调用的是getNode):
public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; }
get 方法看起来就要简单许多了:
从这两个核心方法(get/put)能够看出 1.8 中对大链表作了优化,修改成红黑树以后查询效率直接提升到了 O(logn)。
可是 HashMap 原有的问题也都存在,好比在并发场景下使用时容易出现死循环,以下示例:
final HashMap<String, String> map = new HashMap<String, String>(); for (int i = 0; i < 1000; i++) { new Thread(new Runnable() { @Override public void run() { map.put(UUID.randomUUID().toString(), ""); } }).start(); }
可是为何呢?咱们来简单分析一下。上文中提到在 HashMap 扩容的时候会调用 resize() 方法,就是这里的并发操做容易在一个桶上造成环形链表;这样当获取一个不存在的 key 时,计算出的 index 正好是环形链表的下标就会出现死循环。
咱们先来看单线程下的rehash过程,以下图:
多线程并发下的rehash过程,以下图:
还有一个值得注意的是 HashMap 的遍历方式,一般有如下几种:
public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.put("b", 2); Iterator<Map.Entry<String, Integer>> entryIterator = map.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry<String, Integer> next = entryIterator.next(); System.out.println("key=" + next.getKey() + " value=" + next.getValue()); } Iterator<String> iterator = map.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); System.out.println("key=" + key + " value=" + map.get(key)); } // 等同于第一种方式 for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println("key=" + entry.getKey() + " value=" + entry.getValue()); } }
强烈建议使用 EntrySet 进行遍历。第一种和第三种遍历方式均可以把 key value 同时取出,而第二种还得须要经过 key 取一次 value,效率较低。
简单总结下 HashMap:
不管是 1.7 仍是 1.8 其实都能看出 JDK 没有对它作任何的同步操做,因此并发会出问题,甚至出现死循环致使系统不可用。
所以 JDK 推出了专项专用的 ConcurrentHashMap ,该类位于 java.util.concurrent 包下,专门用于解决并发问题。坚持看到这里的朋友算是已经把 ConcurrentHashMap 的基础已经打牢了,下面正式开始分析。
ConcurrentHashMap 一样也分为 1.7 、1.8 版,因此二者在实现上略有不一样。一样的,咱们先来看看 1.7 的实现,下面是它的结构图:
如图所示,是由 Segment 数组、HashEntry 组成,和 HashMap 同样,仍然是数组加链表。
它的核心成员变量:
/** * Segment 数组,存放数据时首先须要定位到具体的 Segment 中。 */ final Segment<K,V>[] segments; transient Set<K> keySet; transient Set<Map.Entry<K,V>> entrySet;
其中Segment 是 ConcurrentHashMap 的一个内部类,主要的组成以下:
static final class Segment<K,V> extends ReentrantLock implements Serializable { private static final long serialVersionUID = 2249069246763182397L; // 和 HashMap 中的 HashEntry 做用同样,真正存放数据的桶 transient volatile HashEntry<K,V>[] table; transient int count; transient int modCount; transient int threshold; final float loadFactor; }
看看其中 HashEntry 的组成:
和 HashMap 很是相似,惟一的区别就是其中的核心数据如 value ,以及链表都是 volatile 修饰的,保证了获取时的可见性。
原理上来讲:
ConcurrentHashMap 采用了分段锁技术,其中 Segment 继承于 ReentrantLock。不会像 HashTable 那样不论是 put 仍是 get 操做都须要作同步处理,理论上 ConcurrentHashMap 支持 CurrencyLevel (Segment 数组数量)的线程并发。每当一个线程占用锁访问一个 Segment 时,不会影响到其余的 Segment。
下面也来看看核心的 put get 方法。
put 方法:
public V put(K key, V value) { Segment<K,V> s; if (value == null) throw new NullPointerException(); int hash = hash(key); int j = (hash >>> segmentShift) & segmentMask; if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck (segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment s = ensureSegment(j); return s.put(key, hash, value, false); }
首先是经过 key 定位到 Segment,以后在对应的 Segment 中进行具体的 put:
final V put(K key, int hash, V value, boolean onlyIfAbsent) { HashEntry<K,V> node = tryLock() ? null : scanAndLockForPut(key, hash, value); V oldValue; try { HashEntry<K,V>[] tab = table; int index = (tab.length - 1) & hash; HashEntry<K,V> first = entryAt(tab, index); for (HashEntry<K,V> e = first;;) { if (e != null) { K k; if ((k = e.key) == key || (e.hash == hash && key.equals(k))) { oldValue = e.value; if (!onlyIfAbsent) { e.value = value; ++modCount; } break; } e = e.next; } else { if (node != null) node.setNext(first); else node = new HashEntry<K,V>(hash, key, value, first); int c = count + 1; if (c > threshold && tab.length < MAXIMUM_CAPACITY) rehash(node); else setEntryAt(tab, index, node); ++modCount; count = c; oldValue = null; break; } } } finally { unlock(); } return oldValue; }
虽然 HashEntry 中的 value 是用 volatile 关键词修饰的,可是并不能保证并发的原子性,因此 put 操做时仍然须要加锁处理。
首先第一步的时候会尝试获取锁,若是获取失败确定就有其余线程存在竞争,则利用 scanAndLockForPut() 自旋获取锁。
源码说明:
再结合图看看 put 的流程:
get 方法:
public V get(Object key) { Segment<K,V> s; // manually integrate access methods to reduce overhead HashEntry<K,V>[] tab; int h = hash(key); long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE; if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null && (tab = s.table) != null) { for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE); e != null; e = e.next) { K k; if ((k = e.key) == key || (e.hash == h && key.equals(k))) return e.value; } } return null; }
get 逻辑比较简单:
1.7 已经解决了并发问题,而且能支持 N 个 Segment 这么屡次数的并发,但依然存在 HashMap 在 1.7 版本中的问题。那就是查询遍历链表效率过低。所以 1.8 作了一些数据结构上的调整。
首先来看下底层的组成结构:
看起来是否是和 1.8 HashMap 结构相似?其中抛弃了原有的 Segment 分段锁,而采用了 CAS + synchronized 来保证并发安全性:
也将 1.7 中存放数据的 HashEntry 改成 Node,但做用都是相同的。其中的 val next 都用了 volatile 修饰,保证了可见性。
重点来看看 put 方法:
源码说明:
get 方法:
源码说明:
1.8 在 1.7 的数据结构上作了大的改动,采用红黑树以后能够保证查询效率(O(logn)),甚至取消了 ReentrantLock 改成了 synchronized,这样能够看出在新版的 JDK 中对 synchronized 优化是很到位的。
看完了整个 HashMap 和 ConcurrentHashMap 在JDK 1.7 和 1.8 中不一样的实现方式相信你们对他们的理解应该会更加到位。其实这块也是面试的重点内容,一般的套路是:
这一串问题相信你们仔细看完都能怼回面试官。除了面试会问到以外平时的应用其实也蛮多,像以前谈到的 Guava 中 Cache 的实现就是利用 ConcurrentHashMap 的思想。同时也能学习 JDK 做者大牛们的优化思路以及并发解决方案。