Orest
Orest

Reputation: 6748

Performance difference for Future get with timeout vs CompletionService poll with timeout

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.

Upvotes: 0

Views: 827

Answers (0)

Related Questions