I want to return from my executeTasks()
method only after all the tasks submitted to the threadpool are finished. Please note that my thread pool has configurable threadpoolsize and uses SynchronousQueue
as the backing queue, so my for loop proceeds safely by submitting a task only if a thread is available. So, I just want to wait for the final tasks. I am using Phaser
for this.
I've created a Phaser with 1 registered party i.e., the current thread and I register a new party to the Phaser before submitting a task to the threadpool, when the task finishes I deregister the task party. When for loop finishes by submitting the final tasks, I am hoping that my arriveAndAwaitAdvance()
will wait for registered parties to arrive but it will only discover that all those parties are deregistered after some time and then move forward and return from my method.
I think that this will solve my problem. Please let me know if I am wrong or if there is any other better way to do this. Countdownlatch is not going to help as my threadpoolsize is configurable. I know that having a counter and monitor will solve this problem but I want out-of-the-box solution like Phaser.
private void executeTasks(TheadPoolExecutor threadPool, Iterator<String> it) {
final Phaser phaser = new Phaser(1);
for (final String id : IteratorUtils.iterable(it)) {
phaser.register();
threadPool.execute(() -> {
// phaser.arrive();
try {
thread.sleep(10000 * id.length());
} finally {
phaser.arriveAndDeregister();
}
});
}
phaser.arriveAndAwaitAdvance();
phaser.arriveAndDeregister();
}