views:

107

answers:

4

I can't use shutdown() and awaitTermination() because it is possible new tasks will be added to the ThreadPoolExecutor while it is waiting.

So I'm looking for a way to wait until the ThreadPoolExecutor has emptied it's queue and finished all of it's tasks without stopping new tasks from being added before that point.

If it makes any difference, this is for Android.

Thanks

+4  A: 

If you are interested in knowing when a certain task completes, or a certain batch of tasks, you may use ExecutorService.submit(Runnable). Invoking this method returns a Future object which may be placed into a Collection which your main thread will then iterate over calling Future.get() for each one. This will cause your main thread to halt execution until the ExecutorService has processed all of the Runnable tasks.

Collection<Future<?>> futures = new LinkedList<Future<?>>();
futures.add(executorService.submit(myRunnable));
for (Future<?> future:futures) {
    future.get();
}
Tim Bender
+1 That seems to be the best way. Has to be done at the application level, however, where you submit the task, not at the executor service level.
Thilo
+1, or use invokeAll() on a batch of tasks, to await completion. See my answer here: http://stackoverflow.com/questions/3269445/executorservice-how-to-wait-for-all-tasks-to-finish/3269888
andersoj
Right, if you are willing to make your tasks `Callable` instead of `Runnable`, the solution referenced by @andersoj is much simpler.
Tim Bender
Y, and note `Runnable`->`Callable` is trivial with the convenience method `Executors.callable()`
andersoj
Does the invokeAll() approach require knowing all of the tasks ahead of time? This is for an unknown number of tasks and with the possibility that tasks will be added to the queue even while it is waiting. Thanks for all of the great suggestions.
littleFluffyKitty
Also, for the Future approach, will the for loop run into problems if something is added to both the executorService and the futures collection while the loop is looping?
littleFluffyKitty
Yes, `invokeAll()` would require knowing and waiting to submit a block of tasks at a single point in time--otherwise I would have added it as a full-fledged answer to your question. @Thilo's `CompletionService` answer has a weaker, but similar, constraint. I believe @Thilo had a now-deleted answer which was correct for your stated question.
andersoj
@littleFluffyKitty, the `Future` approach in this answer is more or less equivalent to the `invokeAll()` solution. Since the `futures` collection is effectively immutable, it won't have trouble per se with new tasks added -- the snippet or `invokeAll()` will block until the tasks in question (here, whatever myRunnables have been added) complete.
andersoj
@andersoj and @littleFluffyKitty, the code I posted is roughly equivalent to invokeAll(), however, calls to `submit` could just as easily place the `Future` instances into a `BlockingQueue` and then the main thread could do a timed `poll` on the BlockingQueue, providing you the flexibility to wait until the executor has been empty for some time, providing all futures are placed in the same queue.
Tim Bender
@Tim Bender, agreed, your approach could be expanded to be more flexible... with attendant complexity (due to the partial synchrony exposed) levied on the caller. What does it mean for the queue to be momentarily empty?
andersoj
@Tim Bender, in your original answer, is it possible there will be memory leaks because of the linkedlist holding onto the futures? How can I be sure those references are not held?
littleFluffyKitty
@littleFluffyKitty, In the original answer, the memory for the LinkedList will exist in the heap space so long as the variable is in scope and continues to point at that data structure in the heap. If you define the variable locally as part of some method, it will exist for the duration of the method. I don't really know how you intend to use this snippet. Of course, I am thinking like a Java developer, and Android is NOT Java.
Tim Bender
+1  A: 

Maybe you are looking for a CompletionService to manage batches of task, see also this answer.

Thilo
A: 

I think this is a related question: http://stackoverflow.com/questions/3402895/java-threadpool-usage. You might want to check out the answers listed there...

sjlee
+1  A: 

(This is an attempt to reproduce Thilo's earlier, deleted answer with my own adjustments.)

I think you may need to clarify your question since there is an implicit infinite condition... at some point you have to decide to shut down your executor, and at that point it won't accept any more tasks. Your question seems to imply that you want to wait until you know that no further tasks will be submitted, which you can only know in your own application code.

The following answer will allow you to smoothly transition to a new TPE (for whatever reason), completing all the currently-submitted tasks, and not rejecting new tasks to the new TPE. It might answer your question. @Thilo's might also.

Assuming you have defined somewhere a visible TPE in use as such:

AtomicReference<ThreadPoolExecutor> publiclyAvailableTPE = ...;

You can then write the TPE swap routine as such. It could also be written using a synchronized method, but I think this is simpler:

void rotateTPE()
{
   ThreadPoolExecutor newTPE = createNewTPE();
   // atomic swap with publicly-visible TPE
   ThreadPoolExecutor oldTPE = publiclyAvailableTPE.getAndSet(newTPE);
   oldTPE.shutdown();

   // and if you want this method to block awaiting completion of old tasks in  
   // the previously visible TPE
   oldTPE.awaitTermination();
} 

Alternatively, if you really no kidding want to kill the thread pool, then your submitter side will need to cope with rejected tasks at some point, and you could use null for the new TPE:

void killTPE()
{
   ThreadPoolExecutor oldTPE = publiclyAvailableTPE.getAndSet(null);
   oldTPE.shutdown();

   // and if you want this method to block awaiting completion of old tasks in  
   // the previously visible TPE
   oldTPE.awaitTermination();
} 

Which could cause upstream problems, the caller would need to know what to do with a null.

You could also swap out with a dummy TPE that simply rejected every new execution, but that's equivalent to what happens if you call shutdown() on the TPE.

andersoj
Thanks for taking the time to write this out, I'll take a look at everything and see which route works best.
littleFluffyKitty