ExecutorCompletionService? Why do need one if we have invokeAll?

后端 未结 4 1751
渐次进展
渐次进展 2020-12-04 09:48

If we use an ExecutorCompletionService we can submit a series of tasks as Callables and get the result interacting with the CompletionService as a

4条回答
  •  青春惊慌失措
    2020-12-04 10:14

    Using a ExecutorCompletionService.poll/take, you are receiving the Futures as they finish, in completion order (more or less). Using ExecutorService.invokeAll, you do not have this power; you either block until are all completed, or you specify a timeout after which the incomplete are cancelled.


    static class SleepingCallable implements Callable {
    
      final String name;
      final long period;
    
      SleepingCallable(final String name, final long period) {
        this.name = name;
        this.period = period;
      }
    
      public String call() {
        try {
          Thread.sleep(period);
        } catch (InterruptedException ex) { }
        return name;
      }
    }
    

    Now, below I will demonstrate how invokeAll works:

    final ExecutorService pool = Executors.newFixedThreadPool(2);
    final List> callables = Arrays.asList(
        new SleepingCallable("quick", 500),
        new SleepingCallable("slow", 5000));
    try {
      for (final Future future : pool.invokeAll(callables)) {
        System.out.println(future.get());
      }
    } catch (ExecutionException | InterruptedException ex) { }
    pool.shutdown();
    

    This produces the following output:

    C:\dev\scrap>java CompletionExample
    ... after 5 s ...
    quick
    slow
    

    Using CompletionService, we see a different output:

    final ExecutorService pool = Executors.newFixedThreadPool(2);
    final CompletionService service = new ExecutorCompletionService(pool);
    final List> callables = Arrays.asList(
        new SleepingCallable("slow", 5000),
        new SleepingCallable("quick", 500));
    for (final Callable callable : callables) {
      service.submit(callable);
    }
    pool.shutdown();
    try {
      while (!pool.isTerminated()) {
        final Future future = service.take();
        System.out.println(future.get());
      }
    } catch (ExecutionException | InterruptedException ex) { }
    

    This produces the following output:

    C:\dev\scrap>java CompletionExample
    ... after 500 ms ...
    quick
    ... after 5 s ...
    slow
    

    Note the times are relative to program start, not the previous message.


    You can find full code on both here.

提交回复
热议问题