Advanced Multi Threading in Java [ Latch ] - Part 1

CountDown latch is one of the kinds of synchronizer which wait for another thread before performing the tasks or This is used to synchronize one or more tasks by enabling them to wait for the tasks completed by other tasks.  It was introduced in Java 5 along with other CyclicBarrier, Semaphore, CuncurrentHashMap and BlockingQueue. Its somehow like the wait and notify but in the more simpler form and will much less code.

It basically works in the latch principle. Or let us suppose we have a seller who is going to sell 10 (No. of operations) apples. The number of customers may be anything but what the seller is concerned about is the number of apples because when it reaches to 0 he can go home. The seller(Main Thread) will wait for the customers (awaits()). Let's say there are 10 customers(Threads) now who are in the line to buy Apple. When one customer buys that Apple then the number of apple decrease by 1 (countdown()) and another customer will get a chance to buy that apple so on the number of apples goes on decreases and finally become 0. After no apples left in the bucket, the seller can stop selling and go home happily. 

Note:: In CountDown Latch the countdown cannot be reset. 


Image result for CountDownLatch

Let's have a look at Java code::




#HappyCoding #CodingWorkspace

1 comment:

  1. Very impressive article. Hope to see more from you.

    ReplyDelete