0

Let's say I have a long running operation from which I would like to get the result or timeout if it takes too long.

There are 2 different version that I would like to compare:

1) When we call poll we check if any items were enqueued into internal blocking queue

ExecutorService executorService = Executors.newFixedThreadPool(4);
CompletionService<String> completionService = new ExecutorCompletionService<>(executorService);

Future<String> future = completionService.submit(() -> {...});
final Future<String> result = completionService.poll(30, TimeUnit.SECONDS);
if (result != null) {
   ...
}

2) When we call get we have the implementation from FutureTask to wait

ExecutorService executorService = Executors.newFixedThreadPool(4);
Future<String> future = executorService.submit(() -> {...});
try {
   String result = future.get(30, TimeUnit.SECONDS);
} catch (TimeoutException e) {
   ...
}

Basically in both versions we're waiting for the future to finish its execution, but the internal implementation is different. Would there be any difference in terms of performance? I've seen this answer which compares CompletionService with CompletableFuture and says that there should be https://stackoverflow.com/a/52980559/2055854. Would it be the same for FutureTask implementation? If yes, would be great to hear better explanation why.

Orest
  • 6,548
  • 10
  • 54
  • 84
  • 2
    You should forget about this answer, it’s nonsense. The waiting routines of these concurrency APIs have been developed by the same experts and won’t differ significantly. It makes no relevant difference whether you wait on a `FutureTask` or wait on a `BlockingQueue`. So the second example is simpler and omits the creation and use of a `BlockingQueue`. The only thing that can be more efficient, is not to wait at all, e.g. `CompletableFuture.supplyAsync(() -> {...}, executorService).thenAccept(result -> { … });` will execute the consumer once the result is available, so no thread is waiting. – Holger Jan 31 '20 at 17:32
  • Ok cool, that makes sense. Thanks! – Orest Jan 31 '20 at 18:49

0 Answers0