HashMap是我們在編程中最常用的map,也是面試中經常考的問題,所以打算深入研究一下hashmap的源碼,並且對比7和8中的不同。一、hashmap的數據結構 hashmap的數據結構是哈希表,核心是基於哈希值的桶,而哈希桶的底層實現其實是數組,數組這種數據結構查找的時間複雜度是O(1),所以哈 ...
HashMap是我們在編程中最常用的map,也是面試中經常考的問題,所以打算深入研究一下hashmap的源碼,並且對比7和8中的不同。
一、hashmap的數據結構
hashmap的數據結構是哈希表,核心是基於哈希值的桶,而哈希桶的底層實現其實是數組,數組這種數據結構查找的時間複雜度是O(1),所以哈希表的查找、刪除、插入的**平均時間複雜度**就是O(1),但是它也有一個致命的缺陷---哈希碰撞(collision),所謂碰撞,舉例說明:兩個數據映射出來的哈希值相同,就會發生哈希碰撞(衝突)。下麵我們來看下java7和java8分別是怎麼解決碰撞問題的。
二、Java 7 HashMap(不是線程安全的)
經典的哈希表的實現---**數組+鏈表**,即如果put到的位置有值了,如果key不一致,則會將新put進來的數據放到這個位置原有值的後面,形成鏈表。畫了個圖簡單展示下:
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/2020032200482239.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzM3ODQxNDc3,size_16,color_FFFFFF,t_70#pic_center)
先來看幾個重要的常量,簡單的介紹我已經寫在了下麵的註釋中了,其實就是把他給的英文註釋簡單翻譯一下,他給的英文註釋很清晰明瞭了
/**
* The default initial capacity - MUST be a power of two.
* 預設的初始化容量,必須是2的冪次方,預設容量是16(2^4)
* 疑問一:為什麼必須是2的冪次方,這樣賦值的目的是什麼?
*/
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.
* 載入因數,預設0.75,載入因數用來判斷什麼時候需要對hashmap進行resize()
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
這裡有個疑問,就是**為什麼初始化容量一定是2^n**,這個我們先留著,稍後進行解答。
下麵我們先去看下他的預設構造函數HashMap()
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
* 預設的構造函數,初始容量為16,載入因數為0.75
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
當然,還有可調初始容量和載入因數的構造函數
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;
this.threshold = tableSizeFor(initialCapacity);
}
/**
* Inflates the table
*/
private vois inflateTable(int toSize) {
iint capacity=roundUpToPowerOf2(toSize);
...//實際開闢空間存儲元素
}
這裡有一個需要註意的地方,當你輸入的initialCapacity不是2^n,roundUpToPowerOf2(param)方法會自動將你輸入的值調整為離他最大的 2的冪次方。這裡說一句,並不是調用了構造函數的時候就會開闢空間,而是等到調用put方法時才會真正開闢空間存儲元素(預設16)。
如何確定這個obj應該對應哪個哈希桶的索引呢?
hashcode的值有-2^(31) ~2^(31)-1,約有42億個數,預設的哈希桶的容量是16,那麼要把這些數據映射到16個桶中,我們都知道求模取餘運算,但是這種方法有兩個缺點:
(1)負數求模是負數,所以這裡就需要將負數變成正數再取餘
(2)慢!
當然,在hashmap中並不是這樣的,我們看下indexFor(param)方法,這個方法就是用來解決這個問題的
```
static int indexFor(int h, int length){
return h & (length-1);
}
```
即用得到的哈希值對數組的長度進行按位與操作,下麵這張圖解釋了為什麼初始容量要是2^(n)
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20200322002301565.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzM3ODQxNDc3,size_16,color_FFFFFF,t_70#pic_center)
***劃重點!!!***
**首先,若初始容量總為2^n,那麼-1就可以得到全為1的二進位數,若(length-1)的二進位數並不總為1,h與這個二進位數進行&操作時,某一位永遠為0,這個時候會出現某個桶永遠不會被選中,始終為空;
其次,再進行&操作的時候,才能非常快速的拿到數組下標,並且分佈還是均勻的。**
接下來,來聊一聊jdk1.7中 hash(obj) 方法:
```
final int hash(Object k){
int h=hashSeed;
if(0 != h && k instanceof String){
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
h ^= (h >>> 20) ^ (h>>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
```
從上述貼的代碼塊中,可以看到先做了一次異或,而後又做了一堆異或。這個方法的註釋解釋為:獲取這個對象的哈希值,然後進行一次補充哈希運算,得到返回結果的哈希值,他能夠防禦設計的非常的差的分佈非常不均勻的哈希函數。如果不這樣的話,就可能遇到嚴重的哈希碰撞。這個解釋已經很清楚了,我就不再贅述了,不過這塊在java8中已經被拋棄了。
然後我們來說一下**擴容**,字面意思看,就是hashmap滿了,需要增大容量,直接貼代碼看一下
```
/**
*新的容量是老的容量的兩倍,在遷移數據的過程中涉及了一個rehash操作transfer(param)
*/
void resize(int newCapacity){
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if(oldCapacity == MAXIMUM_CAPACITY){
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Ebtry[newCapacity];
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
threshold = (int) Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY+1);
}
```
java7中HashMap存在的問題
(1)容易碰到死鎖,形成鏈表閉環(多線程情況下)
這裡簡單解釋一下為什麼會碰到死鎖?
我先把擴容的transfer()方法代碼塊貼上來
```
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
```
假設當前有兩個線程都在進行put操作,分別是線程A和線程B,put的哈希桶的位置已經是一個鏈表了,鏈表長度為2,第一個節點的key為key1,其next節點為key2。當線程A走到 Entry<K,V> next = e.next;這行代碼時,e指向key1,next指向key2。此刻被線程B搶占了cpu,線程B在rehash後,由於使用了頭插法原來的key1->key2變成了key2->key1。這個時候線程A獲得了cpu的使用權,繼續從之前保留的中斷節點開始執行,進入while迴圈, e = next;就會造成死迴圈。
(2)潛在的安全隱患---可以通過進行構造的惡意請求引發DOS,即哈希表完全退化成鏈表,嚴重影響性能
三、Java 8 HashMap(不是線程安全的)
Java 8是對Java 7的改進,為瞭解決上述存在的問題
Java 8採用的是---**數組+鏈表/紅黑樹**,當鏈表長度增加到某閾值(8)時,鏈表將轉變為紅黑樹,並且在元素減少到某閾值時,紅黑樹復準變為鏈表。
為什麼變成紅黑樹的閾值是8呢,其實在Java 8 HashMap的註解中有提到,我把這段註釋也貼了上來:
```
* Because TreeNodes are about twice the size of regular nodes, we
* use them only when bins contain enough nodes to warrant use
* (see TREEIFY_THRESHOLD). And when they become too small (due to
* removal or resizing) they are converted back to plain bins. In
* usages with well-distributed user hashCodes, tree bins are
* rarely used. Ideally, under random hashCodes, the frequency of
* nodes in bins follows a Poisson distribution
* (http://en.wikipedia.org/wiki/Poisson_distribution) with a
* parameter of about 0.5 on average for the default resizing
* threshold of 0.75, although with a large variance because of
* resizing granularity. Ignoring variance, the expected
* occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
* factorial(k)). The first values are:
*
* 0: 0.60653066
* 1: 0.30326533
* 2: 0.07581633
* 3: 0.01263606
* 4: 0.00157952
* 5: 0.00015795
* 6: 0.00001316
* 7: 0.00000094
* 8: 0.00000006
* more: less than 1 in ten million
```
大致翻譯下:若哈希值分佈非常好的情況下,樹是很少被用到的。理想情況下,在桶中節點的個數服從參數為0.5的泊松分佈。即 桶中有0個值的概率是0.6...,所以這就是為什麼選擇閾值為8,超過8這個概率就非常小了,小於十萬分之一。
下麵來看代碼:
幾個重要的常量,中文解釋直接寫在上面了
```
/**
* 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.
* 由鏈表轉變為紅黑樹的閾值-8
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
* 由紅黑樹轉變為鏈表的閾值-6
*/
static final int UNTREEIFY_THRESHOLD = 6;
```
還記得Java 7中的hash()演算法嗎,就是那個裡面一堆異或的演算法,在Java 8中,hash()演算法只有下麵幾行,非常清楚簡單。不過這裡是將h的高16位與低16位進行了異或,在註釋中提到,這樣做也是為了防止低位相同高位不同的情況。
```
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
```
接下來我們看下put()方法
```
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;
//如果找到的對應位置有數據,則對比key是否相同,相同則覆蓋掉
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);
//如果鏈表中元素個數超過TREEIFY_THRESHOLD -1 就執行轉變紅黑樹的方法
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;
}
```
**擴容**
```
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
```
這個註釋我覺得寫的非常好,告訴你在rehash時,原元素要麼保持不變,要麼被遷移到固定的高位,也就是說,加入現在有一個鏈表的元素需要遷移,那麼這些元素去的地方只有兩個位置,一個是原地,一個是固定高位。那這是為什麼?
還記得我們之前分析的如何根據hashcode定位索引嗎,我畫了張圖,方便理解
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20200322021110140.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzM3ODQxNDc3,size_16,color_FFFFFF,t_70#pic_center)
Java 8中還對遷移的元素保留的其原來位置的順序,這樣可以降低出現死鎖概率,並不能避免,畢竟HashMap不是線程安全的。
那麼以上。