why all Future.get() throwing CancelleationException in invokeAll with timeout

I have created one callable which prints couple of lines and sleeps for 2 seconds. I have created a main method which creates 10 instances of this callable and pass to invokeALL method of ExecutorService.

 service.invokeAll(callableList, 3, SECONDS);

when I am iterating returned List of Future objects. I am getting CancellationException.

I am testing whether all future.get() call would cause CancellationException or only those tasks which could could not complete and were cancelled.

I am getting either all results or all CancellationExceptions irrespective of time setting in invokeALL.

I was really expecting that at least some tasks would have complete and returned me results when I call future.get().


Short answer.

All tasks aren't completing in 3 seconds.

Long answer.

The TPE will run all of the tasks and wait for them to complete. It will execute get on each future with the 3 seconds as a wait time for the get method. If all tasks completes in less than 3 seconds the list of Futures will return unaffected.

If it doesn't complete in the expected time then the non-completed futures are cancelled. So if you have 5 tasks and the first 2 completes but 3rd times out, then 3, 4 and 5 are cancelled.

It is stated slightly in the docs

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.

and

Upon return, tasks that have not completed are cancelled.

链接地址: http://www.djcxy.com/p/50184.html

上一篇: ExecutorService.invokeAll并关闭

下一篇: 为什么所有Future.get()在invokeAll中抛出CancelleationException超时