在Brian Goetz的Concurrency In Practice的代码 list 5.19中,他介绍了完成的线程安全的Memoizer类。

我以为我理解了此示例中的代码,除了不了解

while ( true )

用于
public V compute(final A arg) throws InterruptedException

方法。

为什么代码需要while循环?

这是整个代码示例
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);
                if (f == null) { f = ft; ft.run(); }
            }
            try {
                return f.get();
            } catch (CancellationException e) {
                cache.remove(arg, f);
            } catch (ExecutionException e) {
                throw launderThrowable(e.getCause());
            }
        }
    }
}

最佳答案

永恒循环在CancellationException上重试。如果抛出任何其他异常,则执行将停止。

Biotext dot org在同一问题上有一个blog entry

10-08 02:35