How can I hold the main thread until all 5 tasks(threads) have been completed?
class ReadMessages {
private final ExecutorService executorService = Executors.newFixedThreadPool(5);
void readMessage(List<Messages> msg )
{
CountDownLatch latch = new CountDownLatch(msg.size); /// lets say msg.size()=5
for( Messages m : msg) {
executorService.submit(() -> dbservice.processInDB(message)); //execute saveInDb paaralllely in 5 different threads
}
//Hold the main thread until all 5 threads have completed their work. i.e make latch count to 0
//then send email
emailService();
}
You can use the await method of the
CountDownLatchto hold up the thread until the latch reaches zero. You'll want to also modify your submitted task to count down the latch as well. Something like this: