riando um bloqueio baseado em chave (ou mapa de bloquei
Estou tentando projetar um mecanismo de bloqueio baseado em chave: algo como um bloqueio reentrante normal, mas em vez de lock () e unlock (), você bloqueia (chave) e desbloqueia (chave), com o contrato que ninguém poderá bloquear (tecla1) simultaneamente se key.equals (tecla1).
Esse código funcionará? Existem soluções mais eficazes? Eu particularmente não gosto do loop while enquanto tenta colocar a trava no mapa ...
package luca;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantLock;
public class KeyedReentrantLock<K> {
private ConcurrentMap<K, ReentrantLock> lockMap = new ConcurrentHashMap<K, ReentrantLock>();
public void lock(K key) {
ReentrantLock oldLock = lockMap.get(key);
if (oldLock != null && oldLock.isHeldByCurrentThread()){
// increase lock count and return.
oldLock.lock();
return;
}
ReentrantLock newLock = new ReentrantLock();
newLock.lock();
while ((oldLock = lockMap.putIfAbsent(key, newLock)) != null){
// wait for the old lock to be released;
oldLock.lock();
oldLock.unlock();
}
return;
}
public void unlock(K key){
ReentrantLock lock = lockMap.get(key);
if (lock == null) throw new IllegalMonitorStateException("There was no lock for this key!");
if (lock.getHoldCount() == 1){
lockMap.remove(key);
}
lock.unlock();
}
}