Java: Set timeout for threads in a ThreadPool
Have you seen this? ExecutorService.invokeAll
It should be exactly what you want: Invoke a bundle of workers and have them timeout if taking too long.
EDIT after comment - (new idea):You can use a CountDownLatch to wait for the tasks to finish AND timeout via await(long timeout, TimeUnit unit)
!You can then even do a shutdownNow and see which tasks have taken too long ...
EDIT 2:
To make it clearer:
- Have a CountDownLatch be count down by each Worker, when finished.
- In the main execution thread
await
with timeout on said latch. - When that call returns, you can check the Latches's count to see if there has been the timeout hit (if it is >0).
- a) count = 0, all tasks finished in time.b) if not, loop the Futures and check their
isDone
. You don't have to call shutdown on the ExecutorService. - Call shutdown if you do not need the Executor any longer.
Note: Workers can finish in the meantime between the timeout and calling their Future's isDone().