CountdownLatch combine await(maxTime) and countdown()
I have several threads running for an almost infinite time and number of iteration. The iteration count being reset to 0 when a best solution has been found. A max number of iteration is set to prevent an infinite loop.
I use a countdownlatch to stop the process when all thread have reach 开发者_运维百科the max number of iteration. In other word, when a thread reach the max number of iteration, it notifies my main thread using notifyThreadStop() which, when all thread are stopped, triggers countdown().
Note: my threads are running inside a FixedThreadPool ExecutorService.
I would like to add a maxTime latch. So what i did is the following
List<Runnable> r = .... //(contains all my runnables)
myExecutorService.invokeAll(r);
if(maxtime > 0){
mylatch.await(maxTime,TimeUnit.Seconds);
(1)
do stuff...
exit;
}
else{
mylatch.await();
myExecutorService.shutdownNow();
do stuff...
exit;
}
Now, I know that if the countdown has triggered the latch, it means that all threads are stopped so I can shutdownNow my ExecutorService.
It is not the case when the max time has been reached. So in (1) i would like to iterate through all my runners to terminate them in a civilized way :-) . For that, i have defined a function requestTermination() that, simply put, set the iterationCounter to MaxIterationCount in my runnables.
So (1) would become
for(Runnable runner: r){
if(r.getIsRunning()){r.requestTermination();}
}
(2)
Now, I need to wait again until all threads are really stopped before i can proceed.... hmmmm just thinking that i could have an additional latch and work with that.
So (2) would become
mylatch2.await();
myExecutorService.shutdownNow();
Of course, my function notifyThreadStop() would need to be modified of it and would need a flag telling it to do a countdown() on mylatch2 as opposed to mylatch.
I think I have just answered my question but since all this has been written, I'll leave it here for others to refer to it.
The question would now be: Any better way of handling this? Would a shutdownNow() in (1) or (2) be the only thing required? Knowing that my my threads have to close their own log file and shutdown their inner Callable thread*ss* before exiting.
If you use shutdownNow() and awaitTernimation() this will interrupt all running tasks and wait for them to finish.
Provided the tasks can be interuppted and close all resources correct when interrupt, there shouldn't be a problem. (If there is a problem, this is a bug in your task code which you should fix)
I think I have just answered my question but since all this has been written
You did, indeed :-) If there's one thing to add is that you should be careful with RuntimeExceptions, otherwise, your shutdownNow() may never be called. But you knew that already, right?
精彩评论