future java submitall,是否使用invokeAll或submit - java Executor服务

I have a scenario where I have to execute 5 thread asynchronously for the same callable. As far as I understand, there are two options:

1) using submit(Callable)

ExecutorService executorService = Executors.newFixedThreadPool(5);

List> futures = new ArrayList<>();

for(Callable callableItem: myCallableList){

futures.add(executorService.submit(callableItem));

}

2) using invokeAll(Collections of Callable)

ExecutorService executorService = Executors.newFixedThreadPool(5);

List> futures = executorService.invokeAll(myCallableList));

What should be the preferred way?

Is there any disadvantage or performance impact in any of them compared to the other one?

解决方案

Option 1 : You are submitting the tasks to ExecutorService and you are not waiting for the completion of all tasks, which have been submitted to ExecutorService

Option 2 : You are waiting for completion of all tasks, which have been submitted to ExecutorService.

What should be the preferred way?

Depending on application requirement, either of them is preferred.

If you don't to wait after task submit() to ExecutorService, prefer Option 1.

If you need to wait for completion of all tasks, which have been submitted to ExecutorService, prefer Option 2.

Is there any disadvantage or performance impact in any of them compared to the other one?

If your application demands Option 2, you have to wait for completion of all submitted tasks to ExecutorService unlike in Option 1. Performance is not criteria for comparison as both are designed for two different purposes.

And one more important thing : Whatever option you prefer, FutureTask swallows Exceptions during task execution. You have to be careful. Have a look at this SE question: Handling Exceptions for ThreadPoolExecutor

With Java 8, you have one more option : ExecutorCompletionService

A CompletionService that uses a supplied Executor to execute tasks. This class arranges that submitted tasks are, upon completion, placed on a queue accessible using take. The class is lightweight enough to be suitable for transient use when processing groups of tasks.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值