Knowing when all threads terminate and deal with exceptions

I use the Executor framework to start multiple threads using threadpool ie newFixedThreadPool. I use threadpool.submit (aThread) to submit jobs that will be executed using threadpool, and this works fine, but I need to determine when all threads are complete so that I can continue processing. I looked at using Future.get (), which blocks until the thread is completed, and the problem will be that it blocks until the result is received. I also looked at using a continuous call to the isTerminated () method, followed by hibernation after issuing a shutdown, to check if all threads are complete, but that doesn't seem neat to me. Is there an even cleaner way? Also, if there is any exception that has occurred in any of the threads, I wantso that you can complete all other running threads, as well as stop starting any queue in the pool from the pool. What is the best mechanism for doing this?

We look forward to hearing from you.

TIA

+3
source share
2 answers

One of the cleaner ways to approach this is to change the tasks that are presented. By registering a callback with each task, it can notify of the usual completion or exception without any polling on the main thread.

You can write a simple shell that will do this for anyone Runnable.

Or, following this example, you can expand the idea to wrap anyone Callable.

class CallbackTask<T>
  implements Callable<T>
{

  private final Callable<? extends T> task;

  private final Callback<T> callback;

  CallbackTask(Callable<? extends T> task, Callback<T> callback)
  {
    this.task = task;
    this.callback = callback;
  }

  public T call()
    throws Exception
  {
    try {
      T result = task.call();
      callback.complete(result);
      return result;
    }
    catch (Exception ex) {
      callback.failed(ex);
      throw ex;
    }
  }

}
+1
source

Use ExecutorService # shutdown () and then ExecutorService # awaitTermination ()

For example:

ExecutorService service = Executors.newCachedThreadPool();
service.submit(...);
service.submit(...);
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

// All tasks have now finished

. ThreadFactory ExecutorService, " " . .

+7

Source: https://habr.com/ru/post/1717865/


All Articles