Java HashMap 和 ConcurrentHashMap
转自:http://www.codeceo.com/article/java-hashmap-concurrenthashmap.html 前言Map 这样的? 本篇主要想讨论 ConcurrentHashMap 这样一个并发容器,在正式开始之前我觉得有必要谈谈 HashMap,没有它就不会有后面的 ConcurrentHashMap。 HashMap众所周知 HashMap 底层是基于? Base 1.71.7 中的数据结构图: 先来看看 1.7 中的实现。 这是 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(); }
给定的默认容量为 16,负载因子为 0.75。Map 在使用过程中不断的往里面存放数据,当数量达到了? 因此通常建议能提前预估 HashMap 的大小最好,尽量的减少扩容带来的性能损耗。 根据代码可以看到其实真正存放数据的是
这个数组,那么它又是如何定义的呢? 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; }
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,bucketIndex); } void createEntry(int hash,int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<>(hash,e); size++; }
当调用 addEntry 写入 Entry 时需要判断是否需要扩容。 如果需要就进行两倍扩充,并将当前的 key 重新 hash 并定位。 而在? get 方法再来看看 get 函数: 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; }
Base 1.8不知道 1.7 的实现大家看出需要优化的点没有? 其实一个很明显的地方就是:
因此 1.8 中重点优化了这个查询效率。 1.8 HashMap 结构图: 先来看看几个核心的成员变量: 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; static final int TREEIFY_THRESHOLD = 8; 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 一样,存放的都是? 再来看看核心方法。 put 方法看似要比 1.7 的复杂,我们一步步拆解:
get 方法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 中对大链表做了优化,修改为红黑树之后查询效率直接提高到了? 但是 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 扩容的时候会调用? 如下图: 遍历方式 还有一个值得注意的是 HashMap 的遍历方式,通常有以下几种: 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)); }
第一种可以把 key value 同时取出,第二种还得需要通过 key 取一次 value,效率较低。
因此 JDK 推出了专项专用的 ConcurrentHashMap ,该类位于?
ConcurrentHashMapConcurrentHashMap 同样也分为 1.7 、1.8 版,两者在实现上略有不同。 Base 1.7先来看看 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 方法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,false); }
首先是通过 key 定位到 Segment,之后在对应的 Segment 中进行具体的 put。 final V put(K key,int hash,boolean onlyIfAbsent) { HashEntry<K,V> node = tryLock() ? null : scanAndLockForPut(key,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,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 操作时仍然需要加锁处理。 首先第一步的时候会尝试获取锁,如果获取失败肯定就有其他线程存在竞争,则利用?
再结合图看看 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 逻辑比较简单: 只需要将 Key 通过 Hash 之后定位到具体的 Segment ,再通过一次 Hash 定位到具体的元素上。 由于 HashEntry 中的 value 属性是用 volatile 关键词修饰的,保证了内存可见性,所以每次获取时都是最新值。 ConcurrentHashMap 的 get 方法是非常高效的,因为整个过程都不需要加锁。 Base 1.81.7 已经解决了并发问题,并且能支持 N 个 Segment 这么多次数的并发,但依然存在 HashMap 在 1.7 版本中的问题。
因此 1.8 做了一些数据结构上的调整。 首先来看下底层的组成结构: 看起来是不是和 1.8 HashMap 结构类似? 其中抛弃了原有的 Segment 分段锁,而采用了? 也将 1.7 中存放数据的 HashEntry 改为 Node,但作用都是相同的。 其中的? put 方法重点来看看 put 函数:
get 方法
总结看完了整个 HashMap 和 ConcurrentHashMap 在 1.7 和 1.8 中不同的实现方式相信大家对他们的理解应该会更加到位。 其实这块也是面试的重点内容,通常的套路是:
这一串问题相信大家仔细看完都能怼回面试官。 除了面试会问到之外平时的应用其实也蛮多,像之前谈到的?Guava 中 Cache?的实现就是利用 ConcurrentHashMap 的思想。 同时也能学习 JDK 作者大牛们的优化思路以及并发解决方案。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |