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 could wait jobs to finish on a certain interval:
int maxSecondsPerComputeDTask = 20;
try {
while (!es.awaitTermination(uniquePhrases.size() * maxSecondsPerComputeDTask, TimeUnit.SECONDS)) {
// consider giving up with a 'break' statement under certain conditions
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Or you could use ExecutorService.submit(Runnable) and collect the Future objects that it returns and call get() on each in turn to wait for them to finish.
ExecutorService es = Executors.newFixedThreadPool(2);
Collection> futures = new LinkedList<>();
for (DataTable singleTable : uniquePhrases) {
futures.add(es.submit(new ComputeDTask(singleTable)));
}
for (Future> future : futures) {
try {
future.get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
InterruptedException is extremely important to handle properly. It is what lets you or the users of your library terminate a long process safely.