等待未来的清单


145

我有一种返回List期货的方法

List<Future<O>> futures = getFutures();

现在,我要等到所有期货都成功完成处理,或者期货输出返回的任何任务都抛出异常。即使一项任务引发异常,也没有必要等待其他期货。

简单的方法是

wait() {

   For(Future f : futures) {
     try {
       f.get();
     } catch(Exception e) {
       //TODO catch specific exception
       // this future threw exception , means somone could not do its task
       return;
     }
   }
}

但是这里的问题是,例如,如果第4个期货抛出异常,那么我将不必要地等待前3个期货可用。

如何解决呢?会以任何方式倒计时闩锁帮助吗?我无法使用Future,isDone因为Java文档说

boolean isDone()
Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.

1
谁产生那些期货?他们是什么类型的?接口java.util.concurrent.Future没有提供所需的功能,唯一的方法是将自己的Futures与回调一起使用。
阿列克谢·凯戈罗多夫

您可以ExecutionService为每个“批处理”任务创建一个实例,将其提交给它,然后立即关闭服务并awaitTermination()在我想的服务上使用它。
millimoose13年

CountDownLatch如果将所有期货的主体包裹在a中,则可以使用a try..finally来确保闩锁也减小。
millimoose13年


@AlexeiKaigorodov是的,我的未来类型为java.util.concurrent。我正在用callable起诉Future。我将任务提交给execureservice时得到Futture
user93796 2013年

Answers:


124

您可以使用CompletionService在期货准备就绪时立即接收它们,如果其中之一引发异常,则取消处理。像这样:

Executor executor = Executors.newFixedThreadPool(4);
CompletionService<SomeResult> completionService = 
       new ExecutorCompletionService<SomeResult>(executor);

//4 tasks
for(int i = 0; i < 4; i++) {
   completionService.submit(new Callable<SomeResult>() {
       public SomeResult call() {
           ...
           return result;
       }
   });
}

int received = 0;
boolean errors = false;

while(received < 4 && !errors) {
      Future<SomeResult> resultFuture = completionService.take(); //blocks if none available
      try {
         SomeResult result = resultFuture.get();
         received ++;
         ... // do something with the result
      }
      catch(Exception e) {
             //log
         errors = true;
      }
}

我认为,如果其中一个抛出错误,您可以进一步取消任何仍在执行的任务。


1
:您的代码与我在帖子中提到的问题相同。如果将来抛出异常,则代码仍将等待将来的1,2,3完成。还是会把completeSerice.take返回到第一个完成的将来?
user93796

1
超时怎么办?我可以告诉完成服务最大等待X秒吗?
user93796

1
不该有。它不会对期货进行迭代,但是一旦准备就绪,就会立即处理/验证是否抛出异常。
dcernahoschi 2013年

2
要超时等待将来出现在队列中,请在上使用poll(seconds)方法CompletionService
dcernahoschi

这是github上的工作示例:github.com/princegoyal1987/FutureDemo
user18853

107

如果您使用的是Java 8,则可以使用CompletableFuture和CompletableFuture.allOf轻松完成此操作,后者仅在完成所有提供的CompletableFutures之后才应用回调。

// Waits for *all* futures to complete and returns a list of results.
// If *any* future completes exceptionally then the resulting future will also complete exceptionally.

public static <T> CompletableFuture<List<T>> all(List<CompletableFuture<T>> futures) {
    CompletableFuture[] cfs = futures.toArray(new CompletableFuture[futures.size()]);

    return CompletableFuture.allOf(cfs)
            .thenApply(ignored -> futures.stream()
                                    .map(CompletableFuture::join)
                                    .collect(Collectors.toList())
            );
}

3
@Andrejs,您好,您能否解释一下此代码段的作用。我在多个地方都看到了这个建议,但是对于实际发生的事情却感到困惑。如果其中一个线程发生故障,如何处理异常?
VSEWHGHP

2
@VSEWHGHP来自javadoc:如果给定的CompletableFutures中的任何一个异常完成,则返回的CompletableFuture也会这样做,而CompletionException会将此异常作为其原因。
Andrejs

1
对,所以我一直在跟进,有什么办法可以使用此代码段,但可以获取其他所有成功完成的线程的值?我应该只是遍历CompletableFutures列表并调用get来忽略CompletableFuture <List <T >>,因为sequence函数负责确保所有线程都具有结果或异常完成吗?
VSEWHGHP

6
这正在解决另一个问题。如果您有Future实例,则无法应用此方法。转换Future成并不容易CompletableFuture
Jarekczek '18年

如果我们在某些任务中有异常,它将无法正常工作。
slisnychyi

21

使用CompletableFutureJava中8

    // Kick of multiple, asynchronous lookups
    CompletableFuture<User> page1 = gitHubLookupService.findUser("Test1");
    CompletableFuture<User> page2 = gitHubLookupService.findUser("Test2");
    CompletableFuture<User> page3 = gitHubLookupService.findUser("Test3");

    // Wait until they are all done
    CompletableFuture.allOf(page1,page2,page3).join();

    logger.info("--> " + page1.get());

1
这应该是公认的答案。:此外,它的官方Spring文档的一部分 spring.io/guides/gs/async-method
maaw

可以正常工作。
戴蒙

15

您可以使用ExecutorCompletionService。该文档甚至提供了有关您的确切用例的示例:

相反,假设您想使用任务集的第一个非空结果,忽略遇到异常的任何结果,并在第一个任务就绪时取消所有其他任务:

void solve(Executor e, Collection<Callable<Result>> solvers) throws InterruptedException {
    CompletionService<Result> ecs = new ExecutorCompletionService<Result>(e);
    int n = solvers.size();
    List<Future<Result>> futures = new ArrayList<Future<Result>>(n);
    Result result = null;
    try {
        for (Callable<Result> s : solvers)
            futures.add(ecs.submit(s));
        for (int i = 0; i < n; ++i) {
            try {
                Result r = ecs.take().get();
                if (r != null) {
                    result = r;
                    break;
                }
            } catch (ExecutionException ignore) {
            }
        }
    } finally {
        for (Future<Result> f : futures)
            f.cancel(true);
    }

    if (result != null)
        use(result);
}

这里要注意的重要一点是ecs.take()将获得第一个完成的任务,而不仅仅是第一个提交的任务。因此,您应该按照完成执行(或引发异常)的顺序获取它们。


3

如果您使用的是Java 8,并且不想操作CompletableFutures,那么我已经编写了一个工具来检索List<Future<T>>使用流式传输的结果。关键是您不能随意map(Future::get)抛出它。

public final class Futures
{

    private Futures()
    {}

    public static <E> Collector<Future<E>, Collection<E>, List<E>> present()
    {
        return new FutureCollector<>();
    }

    private static class FutureCollector<T> implements Collector<Future<T>, Collection<T>, List<T>>
    {
        private final List<Throwable> exceptions = new LinkedList<>();

        @Override
        public Supplier<Collection<T>> supplier()
        {
            return LinkedList::new;
        }

        @Override
        public BiConsumer<Collection<T>, Future<T>> accumulator()
        {
            return (r, f) -> {
                try
                {
                    r.add(f.get());
                }
                catch (InterruptedException e)
                {}
                catch (ExecutionException e)
                {
                    exceptions.add(e.getCause());
                }
            };
        }

        @Override
        public BinaryOperator<Collection<T>> combiner()
        {
            return (l1, l2) -> {
                l1.addAll(l2);
                return l1;
            };
        }

        @Override
        public Function<Collection<T>, List<T>> finisher()
        {
            return l -> {

                List<T> ret = new ArrayList<>(l);
                if (!exceptions.isEmpty())
                    throw new AggregateException(exceptions, ret);

                return ret;
            };

        }

        @Override
        public Set<java.util.stream.Collector.Characteristics> characteristics()
        {
            return java.util.Collections.emptySet();
        }
    }

这需要AggregateException像C#一样的

public class AggregateException extends RuntimeException
{
    /**
     *
     */
    private static final long serialVersionUID = -4477649337710077094L;

    private final List<Throwable> causes;
    private List<?> successfulElements;

    public AggregateException(List<Throwable> causes, List<?> l)
    {
        this.causes = causes;
        successfulElements = l;
    }

    public AggregateException(List<Throwable> causes)
    {
        this.causes = causes;
    }

    @Override
    public synchronized Throwable getCause()
    {
        return this;
    }

    public List<Throwable> getCauses()
    {
        return causes;
    }

    public List<?> getSuccessfulElements()
    {
        return successfulElements;
    }

    public void setSuccessfulElements(List<?> successfulElements)
    {
        this.successfulElements = successfulElements;
    }

}

此组件的作用与C#的Task.WaitAll完全相同。我正在做一个与CompletableFuture.allOf(等效于Task.WhenAll)相同的变体

我这样做的原因是我正在使用Spring ListenableFutureCompletableFuture尽管它是一种更标准的方式,但也不想移植


1
支持看到等效的AggregateException的支持。
granadaCoder

使用此功能的一个示例会很好。
XDS

1

如果要合并一个CompletableFutures列表,可以执行以下操作:

List<CompletableFuture<Void>> futures = new ArrayList<>();
// ... Add futures to this ArrayList of CompletableFutures

// CompletableFuture.allOf() method demand a variadic arguments
// You can use this syntax to pass a List instead
CompletableFuture<Void> allFutures = CompletableFuture.allOf(
            futures.toArray(new CompletableFuture[futures.size()]));

// Wait for all individual CompletableFuture to complete
// All individual CompletableFutures are executed in parallel
allFutures.get();

有关Future&CompletableFuture的更多详细信息,请参见有用的链接:
1.未来:https
: //www.baeldung.com/java-future 2. CompletableFuture:https
://www.baeldung.com/java-completablefuture 3. CompletableFuture:https ://www.callicoder.com/java-8-completablefuture-tutorial/


0

也许这会有所帮助(没什么可以用原始线程代替的,是的!)我建议Future使用单独的线程(每个线程并行)运行每个家伙,然后当遇到任何错误时,它只是向manager(Handlerclass)发出信号。

class Handler{
//...
private Thread thisThread;
private boolean failed=false;
private Thread[] trds;
public void waitFor(){
  thisThread=Thread.currentThread();
  List<Future<Object>> futures = getFutures();
  trds=new Thread[futures.size()];
  for (int i = 0; i < trds.length; i++) {
    RunTask rt=new RunTask(futures.get(i), this);
    trds[i]=new Thread(rt);
  }
  synchronized (this) {
    for(Thread tx:trds){
      tx.start();
    }  
  }
  for(Thread tx:trds){
    try {tx.join();
    } catch (InterruptedException e) {
      System.out.println("Job failed!");break;
    }
  }if(!failed){System.out.println("Job Done");}
}

private List<Future<Object>> getFutures() {
  return null;
}

public synchronized void cancelOther(){if(failed){return;}
  failed=true;
  for(Thread tx:trds){
    tx.stop();//Deprecated but works here like a boss
  }thisThread.interrupt();
}
//...
}
class RunTask implements Runnable{
private Future f;private Handler h;
public RunTask(Future f,Handler h){this.f=f;this.h=h;}
public void run(){
try{
f.get();//beware about state of working, the stop() method throws ThreadDeath Error at any thread state (unless it blocked by some operation)
}catch(Exception e){System.out.println("Error, stopping other guys...");h.cancelOther();}
catch(Throwable t){System.out.println("Oops, some other guy has stopped working...");}
}
}

我不得不说上面的代码会出错(没有检查),但是我希望我能解释一下解决方案。请尝试一下。


0
 /**
     * execute suppliers as future tasks then wait / join for getting results
     * @param functors a supplier(s) to execute
     * @return a list of results
     */
    private List getResultsInFuture(Supplier<?>... functors) {
        CompletableFuture[] futures = stream(functors)
                .map(CompletableFuture::supplyAsync)
                .collect(Collectors.toList())
                .toArray(new CompletableFuture[functors.length]);
        CompletableFuture.allOf(futures).join();
        return stream(futures).map(a-> {
            try {
                return a.get();
            } catch (InterruptedException | ExecutionException e) {
                //logger.error("an error occurred during runtime execution a function",e);
                return null;
            }
        }).collect(Collectors.toList());
    };

0

CompletionService将使用.submit()方法获取您的Callables,并且您可以使用.take()方法获取计算的期货。

您一定不能忘记的一件事是通过调用.shutdown()方法来终止ExecutorService。同样,只有在保存了对执行程序服务的引用后,才能调用此方法,因此请确保保留其中一个。

示例代码-对于固定数量的要并行处理的工作项:

ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

CompletionService<YourCallableImplementor> completionService = 
new ExecutorCompletionService<YourCallableImplementor>(service);

ArrayList<Future<YourCallableImplementor>> futures = new ArrayList<Future<YourCallableImplementor>>();

for (String computeMe : elementsToCompute) {
    futures.add(completionService.submit(new YourCallableImplementor(computeMe)));
}
//now retrieve the futures after computation (auto wait for it)
int received = 0;

while(received < elementsToCompute.size()) {
 Future<YourCallableImplementor> resultFuture = completionService.take(); 
 YourCallableImplementor result = resultFuture.get();
 received ++;
}
//important: shutdown your ExecutorService
service.shutdown();

示例代码-对于要并行处理的动态数量的工作项:

public void runIt(){
    ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    CompletionService<CallableImplementor> completionService = new ExecutorCompletionService<CallableImplementor>(service);
    ArrayList<Future<CallableImplementor>> futures = new ArrayList<Future<CallableImplementor>>();

    //Initial workload is 8 threads
    for (int i = 0; i < 9; i++) {
        futures.add(completionService.submit(write.new CallableImplementor()));             
    }
    boolean finished = false;
    while (!finished) {
        try {
            Future<CallableImplementor> resultFuture;
            resultFuture = completionService.take();
            CallableImplementor result = resultFuture.get();
            finished = doSomethingWith(result.getResult());
            result.setResult(null);
            result = null;
            resultFuture = null;
            //After work package has been finished create new work package and add it to futures
            futures.add(completionService.submit(write.new CallableImplementor()));
        } catch (InterruptedException | ExecutionException e) {
            //handle interrupted and assert correct thread / work packet count              
        } 
    }

    //important: shutdown your ExecutorService
    service.shutdown();
}

public class CallableImplementor implements Callable{
    boolean result;

    @Override
    public CallableImplementor call() throws Exception {
        //business logic goes here
        return this;
    }

    public boolean getResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }
}

0

我有一个包含以下内容的实用程序类:

@FunctionalInterface
public interface CheckedSupplier<X> {
  X get() throws Throwable;
}

public static <X> Supplier<X> uncheckedSupplier(final CheckedSupplier<X> supplier) {
    return () -> {
        try {
            return supplier.get();
        } catch (final Throwable checkedException) {
            throw new IllegalStateException(checkedException);
        }
    };
}

一旦有了这些,就可以使用静态导入,简单地等待所有这样的期货:

futures.stream().forEach(future -> uncheckedSupplier(future::get).get());

您还可以像这样收集所有结果:

List<MyResultType> results = futures.stream()
    .map(future -> uncheckedSupplier(future::get).get())
    .collect(Collectors.toList());

只需回顾一下我的旧帖子,并注意到您还有另一种悲伤:

但是这里的问题是,例如,如果第4个期货抛出异常,那么我将不必要地等待前3个期货可用。

在这种情况下,简单的解决方案是并行执行此操作:

futures.stream().parallel()
 .forEach(future -> uncheckedSupplier(future::get).get());

这样,第一个异常(尽管不会停止将来)将破坏forEach语句,就像在串行示例中一样,但是由于所有异常并行等待,因此您不必等待前三个完成。


0
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Stack2 {   
    public static void waitFor(List<Future<?>> futures) {
        List<Future<?>> futureCopies = new ArrayList<Future<?>>(futures);//contains features for which status has not been completed
        while (!futureCopies.isEmpty()) {//worst case :all task worked without exception, then this method should wait for all tasks
            Iterator<Future<?>> futureCopiesIterator = futureCopies.iterator();
            while (futureCopiesIterator.hasNext()) {
                Future<?> future = futureCopiesIterator.next();
                if (future.isDone()) {//already done
                    futureCopiesIterator.remove();
                    try {
                        future.get();// no longer waiting
                    } catch (InterruptedException e) {
                        //ignore
                        //only happen when current Thread interrupted
                    } catch (ExecutionException e) {
                        Throwable throwable = e.getCause();// real cause of exception
                        futureCopies.forEach(f -> f.cancel(true));//cancel other tasks that not completed
                        return;
                    }
                }
            }
        }
    }
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        Runnable runnable1 = new Runnable (){
            public void run(){
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
            }
        };
        Runnable runnable2 = new Runnable (){
            public void run(){
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                }
            }
        };


        Runnable fail = new Runnable (){
            public void run(){
                try {
                    Thread.sleep(1000);
                    throw new RuntimeException("bla bla bla");
                } catch (InterruptedException e) {
                }
            }
        };

        List<Future<?>> futures = Stream.of(runnable1,fail,runnable2)
                .map(executorService::submit)
                .collect(Collectors.toList());

        double start = System.nanoTime();
        waitFor(futures);
        double end = (System.nanoTime()-start)/1e9;
        System.out.println(end +" seconds");

    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.