線程安全的簡單HashMap介紹
今天先來講一下HashTable和SynchronizedMap,這兩塊我雖然在面試中沒有回答到過,但是還是決定一起整理下。這兩個類的主要功能跟HashMap相似,不過稍微存在一些區別而已。
HashTable源碼走讀
HashTable說實話我在工作中沒有正在使用過,更多的還是在當初面試題上有過了解,今天就直接看源碼來進行知識鞏固。
首先我們還是從他的數據存儲格式上來看:
private static class Entry<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Entry<K,V> next;
protected Entry(int hash, K key, V value, Entry<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
@SuppressWarnings("unchecked")
protected Object clone() {
return new Entry<>(hash, key, value,
(next==null ? null : (Entry<K,V>) next.clone()));
}
// Map.Entry Ops
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
if (value == null)
throw new NullPointerException();
V oldValue = this.value;
this.value = value;
return oldValue;
}
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&
(value==null ? e.getValue()==null : value.equals(e.getValue()));
}
public int hashCode() {
return hash ^ Objects.hashCode(value);
}
public String toString() {
return key.toString()+"="+value.toString();
}
}
- 這裏千篇一律,主要的一點還是在於它的hashCode方法
public int hashCode() { return hash ^ Objects.hashCode(value); }
這裏的計算方式和HashMap一樣都是key的hashCode與value的hashCode或運算
接下來我們繼續來看它的構造方法源碼:
public Hashtable(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load: "+loadFactor);
if (initialCapacity==0)
initialCapacity = 1;
this.loadFactor = loadFactor;
table = new Entry<?,?>[initialCapacity];
threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
}
- 這裏就比較簡單了,相信大家看懂這個沒有問題,這裏唯一注意點就是HashTable的默認初始容量是11.
後面就是常用操作方法二連get和put,我們先來看get方法:
public synchronized V get(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return (V)e.value;
}
}
return null;
}
- 這裏也比較簡單,我也來說明下,第一個重點是在於在get方法上加了synchronized關鍵字來進行加錯保證線程安全。
- index的計算通過hash與0x7FFFFFFF(這個數字就是2的32次方-1,通俗點就是二進制1-31位都是1),然後進行取模運算,這裏相比HashMap就low了點
我們再來看下put方法:
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
addEntry(hash, key, value, index);
return null;
}
- 這個代碼塊也比較簡單,首先還是一樣,關注它方法上的synchronized關鍵字
- 之後我們可以看到HashTable的value是不允許爲null的
- 之後主要的還是addEntry這個方法,我們來看下
private void addEntry(int hash, K key, V value, int index) {
modCount++;
Entry<?,?> tab[] = table;
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
}
- 這個方法不難,主要還是rehash這個擴容方法的實現
protected void rehash() {
int oldCapacity = table.length;
Entry<?,?>[] oldMap = table;
// overflow-conscious code
int newCapacity = (oldCapacity << 1) + 1;
if (newCapacity - MAX_ARRAY_SIZE > 0) {
if (oldCapacity == MAX_ARRAY_SIZE)
// Keep running with MAX_ARRAY_SIZE buckets
return;
newCapacity = MAX_ARRAY_SIZE;
}
Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];
modCount++;
threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
table = newMap;
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
Entry<K,V> e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = (Entry<K,V>)newMap[index];
newMap[index] = e;
}
}
}
- 我們知道在擴容時我們應該關注的是擴的容量,然後是之前的key-value怎麼重新分配
- 在容量擴容上,我們可以看到每次都是2倍擴容+1,擴容閾值和HashMap相同,都是容量*負載因子
- HashTable是把內部所有的數據都進行了重新計算Hash放入,再回憶下HashMap,我們只需計算一個鏈表內就行,這樣一比我的天效率提升多少數量級啊
關於HashTable大致就講到這,我們接下來繼續分析SynchronizedMap源碼。
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;
}
SynchronizedMap(Map<K,V> m, Object mutex) {
this.m = m;
this.mutex = mutex;
}
到這裏我感覺到有點像裝飾者模式?(個人猜測,如果模式評判不對,請指正)
看完這些,我們繼續來看get、value二連
public V get(Object key) {
synchronized (mutex) {return m.get(key);}
}
public V put(K key, V value) {
synchronized (mutex) {return m.put(key, value);}
}
突然發現就沒啥好說的了,就是幫我們包裝了一層synchronized鎖,這個鎖的粒度是有我們構造方法中可以傳入。