繁体   English   中英

根据此代码,如果返回的Future如何取消FutureTask <V> 被限制在实例中?

[英]According to this code, how could a FutureTask be cancelled if the returned Future<V> is confined in instance?

这是代码:

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) {    <-- line 1
                cache.remove(arg, f);
            } catch (ExecutionException e) {
                throw launderThrowable(e.getCause());
            }
        }
    }
}

line 1捕获了CancellationException ,而Future<V> f被限制在方法中,因此我认为没有人可以调用f.cancel()来取消FutureTask ft

那么第一line 1真的有必要吗?

[…] Future<V> f限制在方法[…]中

这实际上是不正确的。 f作为值存储在cache字段中,其目的是确保仅对任何给定的计算仅执行一次(即使多个线程都需要结果)。

就是说,如果您发布的是整个类定义,并且该类是在其自己的文件中定义的(而不是作为嵌套类,其私有字段对自身外部的某些代码可见),则不会进行任何反射那么,被使用了-您是对的,永远不要引发该异常; 并且由于它不是受检查的异常,因此代码实际上根本不需要确认它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM