假设我有一个长时间运行的操作,如果需要太长时间,我想从中获得结果或超时。
我想比较两个不同的版本:
1)当我们调用时,poll
我们检查是否有任何项目被排入内部阻塞队列
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)当我们调用时,get
我们有FutureTask
等待的实现
ExecutorService executorService = Executors.newFixedThreadPool(4);
Future<String> future = executorService.submit(() -> {...});
try {
String result = future.get(30, TimeUnit.SECONDS);
} catch (TimeoutException e) {
...
}
基本上在这两个版本中,我们都在等待未来完成它的执行,但是内部实现是不同的。在性能方面会有什么不同吗?我已经看到了这个答案,它与 https://stackoverflow.com/a/52980559/2055854 进行比较CompletionService
并说CompletableFuture
应该有。执行上会一样吗?如果是的话,很高兴听到更好的解释。FutureTask