Brian Goetz的Java Concurrency实践提供了一个用于并发使用的高效可伸缩缓存的示例.显示类Memoizer(第108页)实现的示例的最终版本显示了这样的缓存.我想知道为什么这个类没有用@ThreadSafe注释?缓存的客户端类Factorizer已使用@ThreadSafe正确注释.附录指出,如果一个类没有使用@ThreadSafe或@Immutable注释,则应该假定它不是线程安全的.Memoizer似乎是线程安全的.
这是Memoizer的代码:
public class Memoizer<A, V> implements Computable<A, V> {
private final ConcurrentMap<A, Future<V>> cache
= new ConcurrentHashMap<A, Future<V>>();
private final Computable<A, V> c;
public Memoizer(Computable<A, V> c) { this.c = c; }
public V compute(final A arg) throws InterruptedException {
while (true) {
Future<V> f = cache.get(arg);
if (f == null) {
Callable<V> eval = new Callable<V>() {
public V call() throws InterruptedException {
return c.compute(arg);
}
};
FutureTask<V> ft = new FutureTask<V>(eval);
f = cache.putIfAbsent(arg, ft); …Run Code Online (Sandbox Code Playgroud)