Capture a event when all the threads are executed in Executor framework

Im using Java Executor framework to execute multiple threads at a same time. I would like to do some operations after all the threads are executed. Do we have any listeners or event capture mechanism in executor framework

Answer

You might consider moving from a ThreadPoolExecutor to a ScheduledThreadPoolExecutor. The difference is, that for all the tasks you enqueue, you’ll get a Future<T>.

This allows you to check for .isDone() of tasks you submitted and act accordingly. Especially interesting if you need to use results of what you submitted, because you can cleanly perform a .get() then, without blocking the calling thread until the execution is finished.

Another alternative might be to implement a ThreadFactory, which spawns an additional listener thread to join() the main thread and notify you upon completion.

Leave a Reply

Your email address will not be published. Required fields are marked *