public class Demo4_SegmentLock {
private static Integer segments = 16;
private final static Map<Integer, ReentrantLock> lockMaps = new HashMap<>();
public Demo4_SegmentLock() {
init(null, false);
}
private void init(Integer count, boolean fair) {
if (count != null) {
segments = count;
}
for (int i = 0; i < segments; i++) {
lockMaps.put(i, new ReentrantLock(fair));
}
}
public static void lock(Object key) {
ReentrantLock lock = lockMaps.get(key.hashCode() % segments);
lock.lock();
}
public static void unlock(Object key) {
ReentrantLock lock = lockMaps.get(key.hashCode() % segments);
lock.unlock();
}
}