我在资源池的上下文中使用 ReentrantLock 中的条件,据我所见,它简化了线程通信。我的问题是,我最终会有机地编写奇怪的条件语句,例如 acquireMapEmpty、freeQueueNotEmpty、更改等待和单个不同的东西。从技术上讲,它们可以全部被一个条件句替换或分解为更多条件句——是否有经验法则:
- 识别条件
- 弄清楚你是否有太多或太少
- 当你在正确的轨道上或偏离路线时
这是删除资源的示例。
public boolean remove(R resource) throws InterruptedException {
System.out.println("Remove, resource: " + resource + " with thread: " + Thread.currentThread().getName());
if (resource == null) {
throw new NullPointerException();
}
mainLock.lock();
try {
if (!isOpen) {
throw new IllegalStateException("Not open");
}
Object lock = locks.get(resource);
if (lock == null) {
return false;
}
if (freeQueue.remove(resource)) {
locks.remove(resource);
if (!freeQueue.isEmpty()) {
freeQueueNotEmpty.signalAll();
}
return true;
}
while (!freeQueue.contains(resource)) {
change.await();
if (!isOpen) {
throw new IllegalStateException("Not open");
}
lock = locks.get(resource);
if (lock == null) {
return false;
}
}
if (freeQueue.remove(resource)) {
locks.remove(resource);
if (!freeQueue.isEmpty()) {
freeQueueNotEmpty.signalAll();
}
return true;
}
return false;
} finally {
mainLock.unlock();
}
}