Mr. Nicky Mr. Nicky - 1 month ago 7
Java Question

Java: How to tell a threadPool to shutdown, but only after all the submitted tasks are executed?

I'm traversing a file directory tree concurrently and constantly submitting tasks to some threadpools. After the traversing is complete, I want to tell the pools to shutdown, but only after the tasks submitted are complete, because it's entirely possible for the traversing to complete before the tasks are done.

Answer

Presumably you are using an ExecutorService from which you are creating a thread pool then queuing the work on the worker threads of the thread pool.

Shutting the executor service down (and waiting for pending threads to complete their work) is as easy as calling shutdown followed by awaitTermination. After shutdown() is called, no new work is accepted by the executor, and pending work is allowed to complete before shutting down the executor service.

executorSvc.shutdown();          // signal shutdown
while (!executorService.awaitTermination(5, TimeUnit.SECONDS))
    // still processing.. 
    //   you may decide to force shut-down if too much time passes 
}