ITeye博客

ConcurrentHashMap

a123159521 · 2010-10-14 12:05 · JDK · 编程语言 · C · C++ · C# · 多线程 · Markdown

ConcurrentHashMap 这是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更好。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。