对Future.get()块的方法调用。这真的可取吗?

浏览:43日期:2024-02-22
如何解决对Future.get()块的方法调用。这真的可取吗??

Future为您提供isDone()不阻塞的方法,如果计算完成,则返回true,否则返回false。

Future.get() 用于检索计算结果。

您有两种选择:

调用isDone(),如果结果准备就绪,可以通过调用来请求get(),请注意没有阻塞无限期封锁 get()指定超时时间 get(long timeout, TimeUnit unit)

整个Future API过程有一种简单的方法可以从执行并行任务的线程中获取值。如上面的项目符号所述,可以根据需要同步或异步完成此操作。

这是 Java Concurrency In Practice中的 一个缓存实现,是一个非常好的用例Future。

如果计算已经在运行,则对计算结果感兴趣的调用方将等待计算完成如果结果已在缓存中准备好,则调用者将收集它如果结果尚未准备好并且尚未开始计算,则调用方将开始计算并将结果包装在Future其他调用方中。

使用FutureAPI 可以轻松实现所有目标。

package net.jcip.examples;import java.util.concurrent.*;/** * Memoizer * <p/> * Final implementation of Memoizer * * @author Brian Goetz and Tim Peierls */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);// computation not startedif (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); // start computation if it’s not started in the meantime if (f == null) {f = ft;ft.run(); }}// get result if ready, otherwise block and waittry { return f.get();} catch (CancellationException e) { cache.remove(arg, f);} catch (ExecutionException e) { throw LaunderThrowable.launderThrowable(e.getCause());} } }}解决方法

在将此问题标记为重复之前,请仔细阅读问题。

以下是伪代码的代码段。我的问题是-下面的代码是否不会破坏并行异步处理的概念?

我之所以这样问,是因为在下面的代码中,主线程会提交要在其他线程中执行的任务。在队列中提交任务后,它将阻塞Future.get()方法,以使任务返回值。我宁愿在主线程中执行任务,而不是提交到其他线程并等待结果。通过在新线程中执行任务可以得到什么?

我知道您可以等待有限的时间等,但是如果我真的在乎结果怎么办?如果要执行多个任务,问题将变得更加严重。在我看来,我们只是同步进行工作。我知道Guava库提供了一个非阻塞侦听器接口。但是我很想知道我对Future.get()API的理解是否正确。如果是正确的,为什么将Future.get()设计为阻塞从而破坏了并行处理的整个过程?

注意-为了进行记录,我使用JAVA 6

public static void main(String[] args){private ExectorService executorService = ...Future future = executorService.submit(new Callable(){ public Object call() throws Exception {System.out.println('Asynchronous Callable');return 'Callable Result'; }});System.out.println('future.get() = ' + future.get());}

相关文章: