ExecutorService waitTermination method does not work as expected

I am trying to write a process in Java that performs a series of tasks at the same time, waits for tasks to complete, and then completely completes the overall process. Each task has its own information, including when completing a single task. I use ExecutorService for this process and judge the essence of the process as follows:

List<Foo> foos = getFoos();
ExecutorService executorService = Executors.newFixedThreadPool(foos.size());
for (Foo foo : foos) {
    executorService.execute(new MyRunnable(foo));
}

executorService.shutdown();

try {
    executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) {
    // log the error.
}

completeThisProcess();

Each of the MyRunnable objects has a launch method that calls the webservice call and then writes the results of the call to the database, including the time the call ended. The completeThisProcess method simply records the status of the entire process as complete along with the process completion time.

, , , , , completeThisProcess, , , MyRunnables . , , completeThisProcess, 20-30 MyRunnable.

-, , ? , ExecutorService, , awaitTermination , MyRunnable ( , , , ), , , .

+4
1

, , . Callable Runnable ( Callable run) . threadName.

Callable invokeAll, . , MyCallable.

ExecutorService executorService = Executors.newFixedThreadPool(foos.size());
List<Callable> tasks = new ArrayList<>();
for (Foo foo : foos) {
  tasks.add(new MyCallable(foo));
 }
 executorService.invokeAll(tasks);

invokeAll , .

CountDownLatch.

CountDownLatch cdl = new CountDownLatch(foo.size);

cdl.countDown(). cdl.await , , cdl .

+2

All Articles