根据值进行加锁
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public enum ValueLock {
MediaIdLock;
ValueLock() {
for (int i = 0; i < concurrencyLevel; i++) {
locks[i] = new ReentrantLock();
}
}
private int concurrencyLevel = 1 << 8; // 256locks
private Lock[] locks = new Lock[concurrencyLevel];
public Lock getLock(Object key) {
return locks[key.hashCode() & (concurrencyLevel-1)]; // select one of 256 locks
}
// public static void main(String[] args) {
// Lock mediaIdLock = ValueLock.MediaIdLock.getLock(11);
// try {
// mediaIdLock.lock();
// // do something
// } finally {
// mediaIdLock.unlock();
// }
// }
}
网友评论