0

I'm performing a computation using java Callable and ExecutorService:

ExecutorService threadExecutor = Executors.newCachedThreadPool();
for (TaskCallable task: tasks) {
    threadExecutor.submit(task);
}

I want to let the tasks run for at most 2 minutes. but If I call :

task.get(2, TimeUnit.MINUTES);

then it will block immediately! and not let me assign a timeout for the other tasks, until the timeout ends.

I can use

threadExecutor.invokeAll(tasks, 2, TimeUnit.MINUTES);

but it returns List of Futures, and I can't know what task belongs to which Future.

MoneerOmar
  • 205
  • 2
  • 4
  • 18

2 Answers2

0

Use awaitTermination. From docs:

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;
ka4eli
  • 5,294
  • 3
  • 23
  • 43
  • thanks @ka4eli. In fact, I now notice that API says that invokeAll preserves the order of the tasks list: Returns: a list of Futures representing the tasks, **in the same sequential order as produced by the iterator for the given task list.** If the operation did not time out, each task will have completed. If it did time out, some of these tasks will not have completed. – MoneerOmar Aug 10 '15 at 11:20
0

you can use invokeAll since the documentation says:

Returns:
A list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list, each of which has completed.

That all works as expected, when you keep two things in mind:

  • use invokeAll only with a Collection that has a guaranteed order (ArrayList for example and no HashMap)
  • when you iterate over the FutureList you have to check your Future for cancellation (!Future.isCancelled()), otherwise a CancellationException is thrown
BadK
  • 307
  • 3
  • 12