ExecutorService Waiting for Task Completion
In multi-threaded applications, it is often necessary to wait for all tasks submitted to an ExecutorService to complete before proceeding. While crude techniques like polling or constantly checking a global task counter exist, more efficient and elegant solutions are available.
awaitTermination() and shutdown()
The recommended approach involves using the awaitTermination() method of ExecutorService. It allows you to specify a timeout or wait indefinitely for the threads to finish. Here's how it works:
// Create an ExecutorService instance ExecutorService taskExecutor = Executors.newFixedThreadPool(4); // Submit tasks as needed while(...) { taskExecutor.execute(new MyTask()); } // Shutdown the ExecutorService to prevent new tasks from being submitted taskExecutor.shutdown(); // Wait for threads to complete try { taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { // Handle any interruptions }
This method blocks until the threads have completed or the timeout has been reached. You can also specify a finite timeout if you want the application to continue after a specific amount of time, even if some tasks have not finished.
The above is the detailed content of How to Efficiently Wait for ExecutorService Task Completion?. For more information, please follow other related articles on the PHP Chinese website!