【发布时间】:2016-03-11 16:12:10
【问题描述】:
我需要在每个实体 ID 的某些功能中锁定。
private final ConcurrentMap<Long, Lock> idLocks = Maps.newConcurrentMap();
public void doSmth(Long id){
ReentrantLock newLock = new ReentrantLock();
Lock lock = prLocks.putIfAbsent( id, newLock ); //returns null for first run for this id
if (null == lock) { //have to do null checking
lock = newLock;
}
if (lock.tryLock()){
try {
//some code here
} finally {
lock.unlock();
}
}
}
有没有办法运行Lock lock = returnExistingOrPutAndReturnNew( id, newLock ); 来摆脱空值检查?
【问题讨论】:
标签: java concurrency java.util.concurrent