Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

I need to execute some amount of tasks 4 at a time, something like this:

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);

while(...) {

    taskExecutor.execute(new MyTask());

}

//...wait for completion somehow

How can I get notified once all of them are complete? For now, I can't think about anything better than setting some global task counter and decrease it at the end of every task, then monitor in the infinite loop this counter to become 0; or get a list of Futures and in infinite loop monitor isDone for all of them. What are better solutions not involving infinite loops?

Thanks.

1 Answer

0 votes
by (46k points)

Simply on an ExecutorService you call shutdown() and then awaitTermination():

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);

while(...) {

  taskExecutor.execute(new MyTask());

}

taskExecutor.shutdown();

try {

  taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

} catch (InterruptedException e) {

  ...

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...