CountDowaLatch is a high level synchronization utility which is used to prevent a particular thread to start processing until all threads are ready. This is achieved by a count down. The thread, which needs to wait starts with a counter, each thread them make the count down by 1 when they become ready, once the last thread call countDown() method, then latch is broken and the thread waiting with counter starts running. CountDownLatch is a useful synchronizer and used heavily in multi-threaded testing. You can use this class to simulate truly concurrent behavior i.e. trying to access something at same time once every thread is ready. Worth noting is that CountDownLatch starts with a fixed number of counts which cannot be changed later, though this restriction is re-mediated in Java 7 by introducing a similar but flexible concurrency utility called Phaser. There is another similar utility called CyclicBarrier, which can also be used in this situation, where one thread needs to wait for other threads before they start processing. Only difference between CyclicBarrier and CountDownLatch is that you can reuse the barrier even after its broker but you cannot reuse the count down latch, once count reaches to zero. Mastering Concurrency is not easy but if you seriously wants to become an expert Java programmer, you got to tame this horse. One thing which can help you in your journey is the Brian Goetz classic, Java Concurrency in Practice. One of the most recommended book for Java programmer.
Read more »
No comments:
Post a Comment