Providing Java concurrent hash map with lock striping
Implemented a thread-safe StripedConcurrentHashMap in Java using 16 segments, each with its own ReentrantReadWriteLock, allowing concurrent writes to different segments and safe reads/writes within segments. The code includes standard map operations plus a deadlock-safe size method acquiring all read locks in order.
One simple way to get lock striping is to shard your backing map into a fixed number of buckets and protect each bucket with its own lock. The ReentrantReadWriteLock from java.util.concurrent.locks lets you allow concurrent readers while still serialising writers within a segment.
Here's a minimal implementation with 16 stripes:
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class StripedConcurrentHashMap<K,V> {
private static final int NUM_SEGMENTS = 16;
private static final class Segment<K,V> {
final Map<K,V> map = new HashMap<>();
final ReadWriteLock lock = new ReentrantReadWriteLock();
}
@SuppressWarnings("unchecked")
private final Segment<K,V>[] segments = (Segment<K,V>[]) new Segment[NUM_SEGMENTS];
public StripedConcurrentHashMap() {
for (int i = 0; i < NUM_SEGMENTS; i++) {
segments[i] = new Segment<>();
}
}
/** Choose a segment based on the key's hash code. */
private Segment<K,V> segmentFor(Object key) {
int h = (key == null) ? 0 : key.hashCode();
// spread bits a little and mask to 0..15
int idx = (h ^ (h >>> 16)) & (NUM_SEGMENTS - 1);
return segments[idx];
}
public V get(K key) {
Segment<K,V> seg = segmentFor(key);
seg.lock.readLock().lock();
try {
return seg.map.get(key);
} finally {
seg.lock.readLock().unlock();
}
}
public V put(K key, V value) {
Segment<K,V> seg = segmentFor(key);
seg.lock.writeLock().lock();
try {
return seg.map.put(key, value);
} finally {
seg.lock.writeLock().unlock();
}
}
public V remove(K key) {
Segment<K,V> seg = segmentFor(key);
seg.lock.writeLock().lock();
try {
return seg.map.remove(key);
} finally {
seg.lock.writeLock().unlock();
}
}
public boolean containsKey(K key) {
Segment<K,V> seg = segmentFor(key);
seg.lock.readLock().lock();
try {
return seg.map.containsKey(key);
} finally {
seg.lock.readLock().unlock();
}
}
/** Compute size by locking all segments in a fixed order to avoid deadlock. */
public int size() {
// acquire all read locks
for (Segment<K,V> seg : segments) {
seg.lock.readLock().lock();
}
try {
int total = 0;
for (Segment<K,V> seg : segments) {
total += seg.map.size();
}
return total;
} finally {
// release in reverse order
for (int i = segments.length - 1; i >= 0; i--) {
segments[i].lock.readLock().unlock();
}
}
}
}
Because each segment has its own ReadWriteLock, threads operating on different segments do not contend with each other. Two threads can call put on keys that hash to different stripes concurrently. Reads can proceed concurrently with other reads in the same segment by acquiring the readLock(), and writes are serialised per–segment by the writeLock().