并发哈希映射的独占锁

时间:2013-08-21 09:31:32

标签: java synchronization concurrenthashmap

通过链接编写的博客提供了对并发hashmap的独占同步,并说它是面向性能的:exclusive lock for concurrent hash map。我很困惑它是否会在为并发哈希映射提供自定义功能时真正起作用。我也想知道它是否使用与ConcurrentHashMap相同的锁

public class CMap<K, V> {
private final ConcurrentMap<K, V> map = new ConcurrentHashMap<K, V>();
private final Object[] locks = new Object[16]; {
    for(int i = 0;i<locks.length;i++) locks[i] = new Object();
}

public V put(K key, V value) {
    int hash = key.hashCode() & 0x7FFFFFFF;
    synchronized (locks[hash % locks.length]) { // allows concurrent writes.
        return map.put(key, value);
    }
}

public V get(K key) {
    return map.get(key); // concurrent reads.
}

public V putIfAbsentTheHardWay(K key, V value) {
    int hash = key.hashCode() & 0x7FFFFFFF;
    synchronized (locks[hash % locks.length]) { // supports custom operations.
        if (!map.containsKey(key))
            return map.put(key, value);
        else
            return map.get(key);
    }
}

}

0 个答案:

没有答案