What is the simplest way to to wait for all tasks of ExecutorService to finish? My task is primarily computational, so I just want to run a large number of jobs
You can use ExecutorService.invokeAll method, It will execute all task and wait till all threads finished their task.
Here is complete javadoc
You can also user overloaded version of this method to specify the timeout.
Here is sample code with ExecutorService.invokeAll
public class Test {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService service = Executors.newFixedThreadPool(3);
List> taskList = new ArrayList<>();
taskList.add(new Task1());
taskList.add(new Task2());
List> results = service.invokeAll(taskList);
for (Future f : results) {
System.out.println(f.get());
}
}
}
class Task1 implements Callable {
@Override
public String call() throws Exception {
try {
Thread.sleep(2000);
return "Task 1 done";
} catch (Exception e) {
e.printStackTrace();
return " error in task1";
}
}
}
class Task2 implements Callable {
@Override
public String call() throws Exception {
try {
Thread.sleep(3000);
return "Task 2 done";
} catch (Exception e) {
e.printStackTrace();
return " error in task2";
}
}
}