在Java開發中經常會使用到hashmap,對於hashmap又了解多少,經常聽到的一句話是hashmap是線程不安全的,那為什么是線程不安全的,如何才能保證線程安全,JDK又給我們提供了那些線程安全的類,這些問題是今天討論的問題,
一、hashmap為什么線程不安全
說到hashmap為什么線程不安全,首先要理解線程安全的定義。簡單來講,指的就是兩個以上的線程操作同一個hashmap對象,不會發生資源爭搶,hashmap中的數據不會錯亂。根據以上的說法,我們大體上看下hashmap的源碼,分析下其常用方法put、get的源碼。
1、hashmap定義(基於JDK1.8)
經常使用hashmap的方式如下,
HashMap map1=new HashMap();
使用最簡單粗暴的方式創建一個HashMap的對象,那么在底層是如何創建的,查看源碼如下,
/** * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). */ public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
根據上面的提示,可以直到使用這個構造方法創建的對象,其默認初始容量為16,默認的加載因子為0.75。此構造方法就是給loadFactor賦值,賦的為DEFAULT_LOAD_FACTOR其值為0.75,下面看下其一些屬性
/** * 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;
可以看到默認初始容量為(DEFAULT_INITIAL_CAPACITY)1<<4,即1向左移4為,得出為1*2的4次方,為16。下面看還有最大容量(MAXIMUM_CAPACITY)為1<<30,即1向左移30位,得出為1*2的30次方。下面是默認的負載因子。從上面可以得出HashMap是又最大容量限制的,只不過平時使用的時候很少突破其最大容量(突破了就內存溢出了)。其他的構造函數暫時不看,看其put方法,
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
調用了putVal方法,
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
以上便是put方法的全部,代碼邏輯暫不分析,從 代碼中看不到任何有關並發方面的限制,比如使用synchronized關鍵字、使用鎖、CAS等,那么在多個線程同時操作HashMap對象的時候勢必會引起線程安全的問題。下面是其get方法
public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; }
調用了getNode方法,
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; }
從上面的代碼也未看到有關線程並發安全方面的處理。其他方法不一一列舉,我們知道HashMap是線程不安全的。
二、如何保證HashMap的線程安全
從上面的分析,我們知道在對HashMap進行添加/取出操作時未進行線程安全的控制,為了使HashMap是線程安全的,我們可以在對HashMap進行操作時枷鎖,使用synchronized關鍵字或者可重入鎖,
1、synchronized關鍵字
為HashMap的操作加synchronized關鍵字以保證其線程安全,由於synchronized有兩種用法,即可以使用代碼塊及作用於方法上,這里演示作用於方法上,
HashMap map1=new HashMap(); public synchronized void putMap() { map1.put("test", "test"); }
synchronized關鍵字的用法可以再復習下哦。
2、可重入鎖
使用ReentrantLock可重入鎖控制hashMap的插入。
HashMap map1=new HashMap(); public void putMapUseLock() { ReentrantLock rl=new ReentrantLock(); try{ rl.lock(); map1.put("test", "test"); }finally { rl.unlock(); } }
以上時兩種解決HashMap線程不安全的解決思路,那么JDK是否提供了類似的解決方案那。
三、JDK提供的線程安全的HashMap
由於HashMap使用的范圍很廣,所以JDK提供了線程安全的HashMap,說兩個常用的ConcurrentHashMap和synchronizedMap,這兩個都是線程安全的,但其實現原理不盡相同。
1、synchronizedMap
synchronizedMap是Collections類的靜態內部類,使用方法如下,
HashMap map1=new HashMap(); Map map=Collections.synchronizedMap(map1);
使用其靜態方法synchronizedMap,傳入一個Map對象
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) { return new SynchronizedMap<>(m); }
返回的synchronizedMap對象,其構造方法如下,
private final Map<K,V> m; // Backing Map final Object mutex; // Object on which to synchronize SynchronizedMap(Map<K,V> m) { this.m = Objects.requireNonNull(m); mutex = this; }
第一步判斷參數m是否為null,第二步把this賦值給mutex,那么mutex代表什么意思。下面看其一個put操作,
public V put(K key, V value) { synchronized (mutex) {return m.put(key, value);} }
看到上面的方法,想必都很驚訝,使用了synchronized代碼塊,而mutex相當於共享的對象,調用的還是參數m的put方法,所以這里如果m的指向為不安全的HashMap,那么加上synchronized之后便是安全的。
get方法如下,
public V get(Object key) { synchronized (mutex) {return m.get(key);} }
總結下來,SynchronizedMap是使用Synchronized關鍵字實現的。
2、ConcurrentHashMap
通過這個類的名字,可以看出其在java.util.concurrent包下,且是為HashMap提供並發操作的類。其使用方式如下,
ConcurrentHashMap map2=new ConcurrentHashMap();
下面看其構造方法,
/** * Creates a new, empty map with the default initial table size (16). */ public ConcurrentHashMap() { }
很簡潔,通過注釋可得知構造一個空的Map,其容量為16,和HashMap是一樣的,但是這里沒有負載因子。再看其他的構造方法

看下其put/get方法
public V put(K key, V value) { return putVal(key, value, false); } /** Implementation for put and putIfAbsent */ final V putVal(K key, V value, boolean onlyIfAbsent) { if (key == null || value == null) throw new NullPointerException(); int hash = spread(key.hashCode()); int binCount = 0; for (Node<K,V>[] tab = table;;) { Node<K,V> f; int n, i, fh; if (tab == null || (n = tab.length) == 0) tab = initTable(); else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null))) break; // no lock when adding to empty bin } else if ((fh = f.hash) == MOVED) tab = helpTransfer(tab, f); else { V oldVal = null; synchronized (f) { if (tabAt(tab, i) == f) { if (fh >= 0) { binCount = 1; for (Node<K,V> e = f;; ++binCount) { K ek; if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) { oldVal = e.val; if (!onlyIfAbsent) e.val = value; break; } Node<K,V> pred = e; if ((e = e.next) == null) { pred.next = new Node<K,V>(hash, key, value, null); break; } } } else if (f instanceof TreeBin) { Node<K,V> p; binCount = 2; if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key, value)) != null) { oldVal = p.val; if (!onlyIfAbsent) p.val = value; } } } } if (binCount != 0) { if (binCount >= TREEIFY_THRESHOLD) treeifyBin(tab, i); if (oldVal != null) return oldVal; break; } } } addCount(1L, binCount); return null; }
方法名稱和HashMap是一樣的,從putVal方法中看到了synchronized關鍵字,即也是使用synchronized關鍵字實現,但是肯定比synchronizedMap要高效,具體實現邏輯,暫時不分析。
綜述,分析了Java中使用廣泛的HashMap的常用用法及線程安全。
有不正之處,歡迎指正!
