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 want 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 tasks submitted 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.
Have a look at related SE question: ExecutorCompletionService? Why do need one if we have invokeAll?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…