你可以看看源代碼。 (我期待在JDK 6)HashMap.get()是非常簡單的:
public V get(Object key) {
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode());
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.equals(k)))
return e.value;
}
return null;
}
凡散列()做一些額外的轉換和異或「改善」的哈希碼。
ConcurrentHashMap.get()是更復雜一些,但不是很多
public V get(Object key) {
int hash = hash(key.hashCode());
return segmentFor(hash).get(key, hash);
}
同樣,散列()做一些移位和異或運算。 setMentFor(int hash)做一個簡單的數組查找。唯一複雜的東西是在Segment.get()中。但即使這看起來不像火箭科學:
V get(Object key, int hash) {
if (count != 0) { // read-volatile
HashEntry<K,V> e = getFirst(hash);
while (e != null) {
if (e.hash == hash && key.equals(e.key)) {
V v = e.value;
if (v != null)
return v;
return readValueUnderLock(e); // recheck
}
e = e.next;
}
}
return null;
}
獲取鎖的一個地方是readValueUnderLock()。評論說,這在內存模型下在技術上是合法的,但從未發生過。
總的來說,兩個代碼看起來都很相似。在ConcurrentHashMap中組織好一點。所以我猜測性能足夠相似。
這就是說,如果真的是非常罕見的,你可以考慮實現一個「複製寫入」類型的機制。
ConcurrentHashMap是線程安全的。這伴隨着每一項操作的開銷。但是,除非您的應用程序花費90%的時間從中檢索值,否則您不會注意到其中的差異。 – bdares 2012-01-29 03:29:59
你好,爲什麼我會得到一個downvote?請解釋爲什麼! – user1145216 2012-01-29 03:30:02
你看看API嗎?它清楚地表明寫入是同步的,而檢索不是。還有什麼要知道的? – blackcompe 2012-01-29 06:34:51