How Is Countdownlatch Used in Java Multithreading

How is CountDownLatch used in Java Multithreading?

Yes, you understood correctly.
CountDownLatch works in latch principle, the main thread will wait until the gate is open. One thread waits for n threads, specified while creating the CountDownLatch.

Any thread, usually the main thread of the application, which calls CountDownLatch.await() will wait until count reaches zero or it's interrupted by another thread. All other threads are required to count down by calling CountDownLatch.countDown() once they are completed or ready.

As soon as count reaches zero, the waiting thread continues. One of the disadvantages/advantages of CountDownLatch is that it's not reusable: once count reaches zero you cannot use CountDownLatch any more.

Edit:

Use CountDownLatch when one thread (like the main thread) requires to wait for one or more threads to complete, before it can continue processing.

A classical example of using CountDownLatch in Java is a server side core Java application which uses services architecture, where multiple services are provided by multiple threads and the application cannot start processing until all services have started successfully.

P.S.
OP's question has a pretty straightforward example so I didn't include one.

What's the point of CountDownLatch in java?

Semantically, they're different; and that matters, because it makes your code easier to read. When I see a Semaphore, I immediately start thinking "a limited amount of a shared resource." When I see a CountDownLatch, I immediately start thinking "a bunch of threads waiting for the 'go!' signal." If you give me the former in code that actually needs the latter, it's confusing.

In this sense, a Semaphore being used as a CountDownLatch is a bit like a garden-path sentence; while technically correct, it leads people astray and confuses them.

In terms of more pragmatic uses, a CountDownLatch is just simpler if that's all you need. Simpler is better!

As for reusing a CountDownLatch, that would complicate its usage. For instance, let's say you're trying to queue up threads A, B, and C for some work. You have them await on the latch, and then you release it. Then you reset it, presumably to queue up threads D, E and F for some other work. But what happens if (due to a race condition), thread B hasn't actually been released from the first latch yet? What if it hadn't even gotten to the await() call yet? Do you close the gate on it, and tell it to wait with D, E and F for the second opening? That might even cause a deadlock, if the second opening depends on work that B is supposed to be doing!

I had the same questions you did about resetting when I first read about CountDownLatch. But in practice, I've rarely even wanted to reset one; each unit of "wait then go" (A-B-C, then D-E-F) naturally lends itself to creating its own CountDownLatch to go along with it, and things stay nice and simple.

Usage of countDown latch in java

Seems here you don't use multithreading, and all work done in one thread, because of you needn't to use CountDownLatch.

Also latch.await(); hang because it waiting for all count of tasks will be done(seems here it //rows -2 , columns -3 = 6) and call latch.countDown();. Read more about in docs.

Here is simple example of use, where t2 wait for t1:

import java.util.concurrent.CountDownLatch;

public class Test {

public static void main(String... s){
final CountDownLatch cdl = new CountDownLatch(1);

Thread t1 = new Thread(new Runnable() {

@Override
public void run() {
int i = 5;
while(i-- > 0)
System.out.println("t2 wait me");
cdl.countDown();
}
});

Thread t2 = new Thread(new Runnable() {

@Override
public void run() {
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("done");
}
});

t2.start();
t1.start();
}

}

CountDownLatch in Java need additional synchronization?

The CountDownLatch does not guarantee per the mutual exclusion of the accesses to the share data, rather this mechanism is used to synchronized -- in the sense of one waiting for the other -- parallel task among each other. Similar to the functionality provided by a Cyclic barrier. Actually, as you have described this is the reason why you are using this mechanism in your code; to coordinate the execution of the main and the remaining threads.

If the doWork() method contains shared state among threads, which is modified concurrently, then you might have race-condition. Hence, you need to ensure mutual exclusion of that shared using for instance the synchronized clause.

What is the purpose of await() in CountDownLatch?

CountDownLatch is the synchronization primitive which is used to wait for all threads completing some action.

Each of the thread is supposed to mark the work done by calling countDown() method. The one who waits for the action to be completed should call await() method. This will wait indefinitely until all threads mark the work as processed, by calling the countDown(). The main thread can then continue by processing the worker's results for example.

So in your example it would make sense to call await() at the end of main() method:

latch.await();

Note: there are many other use cases of course, they don't need to be threads but whatever that runs usually asynchronously, the same latch can be decremented several times by the same task etc. The above describes just one common use case for CountDownLatch.

CountDownLatch example in Java Concurrency In Practice

This piece of code

Thread t = new Thread() {

public void run() {
try {
startGate.await();
try {
task.run();
} finally {
endGate.countDown();
}
} catch (InterruptedException ignored) { }
}
};

sets up all the threads that will be needed. Each thread will wait on the startGate to be "opened", ie. its count to go to 0. When the threads are done executing the Runnable, ie. run() returns, they will countdown the endGate. That's what this

The first thing each worker thread does is wait on the starting gate;
this ensures that none of them starts working until they all are ready
to start. The last thing each does is count down on the ending gate;

means.

When all the threads are set up, this code is executed.

long start = System.nanoTime();
startGate.countDown();
endGate.await();
long end = System.nanoTime();
return end-start;

The current thread counts down startGate, which allows all the other threads to begin executing their Runnable, ie. task.run(). It then awaits (blocks) on the endGate to be count down to 0. At this point, it calculates how long that took and returns that value. That's what this

this allows the master thread to wait efficiently until the last of
the worker threads has finished, so it can calculate the elapsed time.

means



Related Topics



Leave a reply



Submit