我需要为计算存储器实现一个简单的通用包装器,能够根据需要重置memoized值。计算可能是长时间运行的,因此复位不应该阻塞太长时间 - 理想情况下,它只是将当前状态标记为"脏"并返回。
这就是我的所作所为:
import java.util.concurrent.Callable;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class CachedValue<A> {
private Callable<A> creator;
private Lock computationLock = new ReentrantLock();
private Lock resultLock = new ReentrantLock();
private volatile A cached = null;
private volatile boolean wasCleared = false;
public CachedValue(Callable<A> creator) {
this.creator = creator;
}
public A get() {
if (cached != null) {
return cached;
} else {
computationLock.lock();
try {
if (cached != null) {
return cached;
} else {
while (true) {
wasCleared = false;
A computed = creator.call();
resultLock.lock();
try {
if (!wasCleared) {
cached = computed;
return cached;
}
} finally {
resultLock.unlock();
}
}
}
} finally {
computationLock.unlock();
}
}
}
public void reset() {
resultLock.lock();
try {
cached = null;
wasCleared = true;
} finally {
resultLock.unlock();
}
}
}
它似乎有效,但我并不期望并行编程,所以我可能错过了一些死锁或效率问题?
答案 0 :(得分:1)
您必须保护cached
和wasCleared
变量,因为可以使用reset
方法从一个线程重置这些变量,而get
方法从另一个可以工作的线程调用同一组变量。
您可以在重置方法中使用相同的重入锁定:
public void reset() {
lock.lock();
try {
cached = null;
wasCleared = true;
} finally {
lock.unlock();
}
}