Search code examples
javamultithreadingspring-bootconcurrencycountdownlatch

CountDownLatch to hold the parent thread


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();
        }

Solution

  • You can use the await method of the CountDownLatch to 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:

    void readMessage(List<Messages> msg) {
        CountDownLatch latch = new CountDownLatch(msg.size); /// lets say msg.size()=5
    
        for(Messages m : msg) {
            executorService.submit(() -> {
                try {
                    dbservice.processInDB(m); //execute saveInDb paaralllely in 5 different threads 
                } finally {
                    // One of the messages has been processed, count down the latch by 1
                    latch.countDown();
                }
            });
        }
    
        //Hold the main thread until all 5 threads have completed their work. i.e make latch count to 0 
        try {
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
        
        //then send email
        emailService();
    }