在链接上写的博客以不同的方式在并发哈希映射上提供了独占同步,并说它是面向性能的:并发哈希映射的独占锁。我很困惑在为并发哈希映射提供自定义功能时它是否真的会起作用。另外我想知道它是否使用与 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);
}
}
}