When is an ExecutorService idle?
I have a number of JUnit tests that trigger some complex behaviour involving additional background threads managed by an ExecutorService (in fact a ThreadPoolExecutor). The application should settle down to a well-defined state when the background tasks have been completed, i.e. the ExecutorService is idle because all submitted tasks have been processed and terminated. The problem is that there doesn't seem to be any reliable way to check for this condition. This means that I can't decide when to check for the 'well-defined state'.
Basically I need anisIdle() method which can be used to wait until all submitted requests have been completed. Since there doesn't seem to be any single method that does this I tried to combine all of the methods that looked likely:
publicboolean isIdle(){
return ((requestExecutor.getQueue().size() == 0) &&
(requestExecutor.getTaskCount() == requestExecutor.getCompletedTaskCount()) &&
(requestExecutor.getActiveCount() == 0));
}
but that still doesn't seem to work. Sometimes it seems to return true even when there are still tasks floating around. If you read the relevant javadoc with it's strong caveats about "the returned value is only an approximation" then perhaps that is not so surprising. Is there areliable way to tell whether an ExecutorService is idle? Shutting it down and waiting for it to terminate is not an option!
The only alternative is to go to sleep for a while and hope that everything is finished afterwards but this leads to JUnit tests that are either slow or error-prone (how big should the sleep be?).

