Java.util.concurrent Synchronizers: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 35: Line 35:
     new Thread(new Runnable()  {
     new Thread(new Runnable()  {


    @Override
        @Override
    public void run()  {
        public void run()  {


        // do stuff ...
            // do stuff ...


        try {
            try {


            barrier.await();
                barrier.await();
        }
            }
        catch(Exception e)  {
            catch(Exception e)  {


            log.error("barrier error", e);
                log.error("barrier error", e);


            // ...
                // ...
            }
         }
         }
     }
     }, "Thread #" + i).start();
}, "Thread #" + i).start();
}
      }
 
...
...
</syntaxhighlight>
</syntaxhighlight>

Revision as of 16:50, 23 March 2018

Internal

CountDownLatch

External

Overview

A CountDownLatch is a synchronization tool that allows one or more threads to wait on it until a certain number of operations being performed in other threads completes. The latch is initialized with a count. Any thread calling await() blocks unit the count reaches zero, after which it is released. You can think of those threads as waiting on a gate to open. The count is decremented with countDown(), which can be called in a loop from a single thread, or concurrently from multiple threads. Note that the threads invoking countDown() are not blocked on the latch - they decrement and continue.

Once the count reached zero, the latch cannot be reused. If you need a reusable mechanism, use Cyclic Barrier.

Semaphore

CyclicBarrier

A cyclic barrier is a primitive useful when waiting for all threads in a group to finish work they are doing individually.

final CyclicBarrier barrier = new CyclicBarrier(threadCount, new Runnable() {

    public void run() {
        System.out.print("ALL threads have finished");
    }
});

for(int i = 0; i < threadCount; i ++) {

    new Thread(new Runnable()  {

        @Override
        public void run()  {

            // do stuff ...

            try {

                barrier.await();
            }
            catch(Exception e)  {

                log.error("barrier error", e);

                // ...
            }
        }
    }, "Thread #" + i).start();
}
...