Real Life Examples For CountDownLatch and CyclicBarrier

前端 未结 11 1335
余生分开走
余生分开走 2021-01-30 13:52

One example is given by one of our trainers when he was explaining difference between CountDownLatch and CyclicBarrier.

CountDownLatch: Suppose a stone can be lifted by

11条回答
  •  日久生厌
    2021-01-30 14:29

    Here are my observations : -----> 1. Where to use what : In a Cyclic barrier threads have to wait for other threads to give some output, and then all threads have to resume processing. So after completing its execution, each thread calls await() method and waits. When the barrier detects that all the threads have reached it, it notifies all its waiting threads and they can resume further execution. Barrier keeps track of count.

    In a CountDownLatch single main thread waits for all threads to complete. Each thread reduces the count by 1 after completing execution. After the count reaches 0, the main thread can resume further execution. Main thread keeps track of count.

    Phaser : In both ways, count of threads should be known beforehand. It is not possible to add/remove threads dynamically. If the count is not reached, thread keeping track of count will wait infinitely. With the Phaser, the number of threads can be dynamic and vary with time. It is similar to Cyclic Barrier. Thread registers with a barrier. After completing execution, it has two options. It can signal that it has arrived at the barrier point and without waiting for others it can deregister from the Phaser. Second option is that it can wait for the other registered Threads to arrive at the barrier point.

    1. Counts : While creating a CyclicBarrier the no of worker threads includes main thread if it is also going to wait for other threads to complete. While creating a CountDownLatch just needs to mention how many worker threads main thread will to wait to complete. In CountDownLatch there is the concept of main and worker threads and the main waiting thread is not included in count while creating a latch. Phaser can return the current count of registered Threads.

    2. Intent of await() : In CyclicBarrier :: await() all threads including main thread are equal and wait for each other. Hence await() should be given in all threads(worker as well as main thread). CountDownLatch :: await() is given in main thread only and it makes main thread wait till other worker threads make count to 0. Thus internal implementation of both await() is different. There are two concepts in Phaser :: arrival to the barrier(arrive() and arriveAndDeregister()) and waiting(awaitAdvance(phase_number)) for other threads.

    3. Parties and Waiting threads : CountDownLatch cannot give number of waiting threads but can give parties(cl.getCount()), CyclicBarrier can give no of waiting threads cb.getNumberWaiting(), and parties(cb.getParties())

    4. Work responsibilities : Worker thread in countdownlatch need to do countdown(), and await() is done by one single main thread. In cyclicBarrier worker and main threads all do only await() on each other.

    5. Reuse : CyclicBarrier can be reused. cb.await() works for new threads say t1, t2 and main. And second call to cb.await() for new threads t3,t4 and main also works. Main will wait in both calls, that is system is automatically internally resetting the count(or reset()) after barrier is exitted. CountDownLatch cannot be reused. - cl.await() works for new threads say t1, t2 and main. Main thread waits for t1, t2 to complete. But for second cl.await() call for new threads t3,t4 and main will not wait. Phaser object can be re-used again once all the Threads in the set have crossed the barrier point.

    6. After Finish Events : While creating, no finish event can be given in CountDownLatch but it can be given in CyclicBarrier.

    class MyClass {

    static class MyThread implements Runnable
    {
    
        long waitTime;
        CyclicBarrier cyclicBarrier;
        CountDownLatch countdownlatch;
        Phaser phaser;
    
    
        MyThread(  long waitTime, CyclicBarrier cyclicBarrier, CountDownLatch countdownlatch, Phaser phaser){
            this.waitTime = waitTime;
            this.cyclicBarrier = cyclicBarrier;
            this.countdownlatch = countdownlatch;
            this.phaser = phaser;
            this.phaser.register(); //Note additional step here
        }
    
        @Override
        public void run() {
    
                try {
    
                    Thread.sleep(waitTime);
    
                    // Diff 4 -----> countdownlatch worker threads need to do countdown and await is done by one single main thread
                    //, cyclicBarrier worker threads await on each other
                    countdownlatch.countDown(); 
                    cyclicBarrier.await();
                    phaser.arriveAndAwaitAdvance();
    
                    System.out.println("cyclicBarrier :: " + 
                            ", name :: " + Thread.currentThread().getName() 
                            + ", parties :: " + cyclicBarrier.getParties() 
                            + ", waiting :: "+ cyclicBarrier.getNumberWaiting()); 
    
                    System.out.println("countdownlatch :: " + 
                                "name :: " + Thread.currentThread().getName()  +
                             ", parties :: "+countdownlatch.getCount() +
                             ", waiting :: " + "No method!!" ); 
                    System.out.println("phaser :: " + 
                            "name :: " + Thread.currentThread().getName()  +
                         ", parties :: "+phaser.getRegisteredParties() +
                         ", phase :: " + phaser.getPhase()); 
    
                    phaser.arriveAndAwaitAdvance();
                    System.out.println("phaser :: " + 
                            "name :: " + Thread.currentThread().getName()  +
                         ", parties :: "+phaser.getRegisteredParties() +
                         ", phase :: " + phaser.getPhase());
    
                    phaser.arriveAndAwaitAdvance();
                    System.out.println("phaser :: " + 
                            "name :: " + Thread.currentThread().getName()  +
                         ", parties :: "+phaser.getRegisteredParties() +
                         ", phase :: " + phaser.getPhase());
                    phaser.arriveAndDeregister(); 
                    if (phaser.isTerminated()) { 
                        System.out.println("Phaser is terminated"); 
                    } 
    
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
    
        }
    
    }
    
    public static class MyCBFinishEvent implements Runnable{
    
        public void run() {
    
               System.out.println("All threads have reached common barrier point "
                            + ", CyclicBarrrierFinishEvent has been triggered");
               System.out.println("You can update shared variables if any");
        }
    
    }
    
    public static void main(String [] args) throws InterruptedException, BrokenBarrierException{
        //Diff 1 ----- > No finish event can be given in CountDownLatch
        //Diff 5 ------> CyclicBarrier no of worker threads includes main thread, 
        //CountDownLatch is just how many threads, the main waiting thread is not included in count.
        CyclicBarrier cb = new CyclicBarrier(3, new MyCBFinishEvent());
        CountDownLatch cl = new CountDownLatch(2);
        Phaser ph = new Phaser();
    
        //Diff 2 ----> CountDownLatch cant give num of waiting threads, CyclicBarrier can getNumberWaiting threads
         System.out.println("Start CyclicBarrier - parties :: "+cb.getParties() + ", waiting :: " + cb.getNumberWaiting());
         System.out.println("Start CountDownLatch - parties :: "+cl.getCount() + ", waiting :: " + "No method!!" );
    
        Runnable t1 = new Thread(new MyThread( 10000, cb, cl, ph));
        Runnable t2 = new Thread(new MyThread( 5000, cb, cl,ph));
         Thread tt1 = new Thread(t1, "t1");
         Thread tt2 = new Thread(t2, "t2");
         tt1.start();
         tt2.start();
    
         //Diff 6 ---- > await meaning Main waits for t1 and t2 to complete, 
         //CyclicBarrier all are equal. each thread including main thread, if it wants to wait has to do await. 
         //CountDownLatch concept of waiting and workers. main thread await waits till other worker threads make count to 0.
         cb.await();
         cl.await();
    
         System.out.println("End CyclicBarrier call 1 - parties :: "+cb.getParties() + ", waiting :: " + cb.getNumberWaiting());
         System.out.println("End CountDownLatch call 1 - parties :: "+cl.getCount() + ", waiting :: " + "No method!!" );
    
         System.out.println("main start created t3, t4 - parties :: "+cl.getCount() + ", waiting :: " + "No method!!" );
    
         Runnable t3 = new Thread(new MyThread( 6000, cb, cl,ph));
            Runnable t4 = new Thread(new MyThread( 100, cb, cl,ph));
             Thread tt3 = new Thread(t3, "t3");
    
             Thread tt4 = new Thread(t4, "t4");
    
             tt3.start();
             tt4.start();
    
            //Diff -3 -----> 
             //CyclicBarrier - can be reused, main thread waited for t3, t4 to complete.
             //CountDownLatch - for first cl.await(), main waited... second cl.await() call main did not wait!!! 
             cb.await();
             cl.await();
    
    
             System.out.println("End main - parties :: "+cb.getParties() + ", waiting :: " + cb.getNumberWaiting());
             System.out.println("end main parties :: "+cl.getCount() + ", waiting :: " + "No method!!" );
    
    }
    

    }

提交回复
热议问题