[align=center]ConcurrentHashMap[/align]
这是HashMap的线程安全类.它拥有Hashtable特殊实现。实现线程安全,并不是基本Sync.而是基本ReentrantLock
代码如下:
在put方法开始前和后都进行了锁定.
注意: segmentFor最后调用的是ReentrantLock来实现的
这里采用锁定hash来实现put方法.采用同步后,相对比来说在单线程下效率没有HashMap高,但是在多线程下,线程安全的ConcurrentHashMap
比Sysn的HashMap更好。
这是HashMap的线程安全类.它拥有Hashtable特殊实现。实现线程安全,并不是基本Sync.而是基本ReentrantLock
代码如下:
V put(K key, int hash, V value, boolean onlyIfAbsent) {
lock();
try {
int c = count;
if (c++ > threshold) // ensure capacity
rehash();
HashEntry<K,V>[] tab = table;
int index = hash & (tab.length - 1);
HashEntry<K,V> first = tab[index];
HashEntry<K,V> e = first;
while (e != null && (e.hash != hash || !key.equals(e.key)))
e = e.next;
V oldValue;
if (e != null) {
oldValue = e.value;
if (!onlyIfAbsent)
e.value = value;
}
else {
oldValue = null;
++modCount;
tab[index] = new HashEntry<K,V>(key, hash, first, value);
count = c; // write-volatile
}
return oldValue;
} finally {
unlock();
}
}
在put方法开始前和后都进行了锁定.
public V put(K key, V value) {
if (value == null)
throw new NullPointerException();
int hash = hash(key.hashCode());
return segmentFor(hash).put(key, hash, value, false);
}
注意: segmentFor最后调用的是ReentrantLock来实现的
这里采用锁定hash来实现put方法.采用同步后,相对比来说在单线程下效率没有HashMap高,但是在多线程下,线程安全的ConcurrentHashMap
比Sysn的HashMap更好。