Suppose, you could have created 5 threads to load 5 completely different classes of knowledge then you may create a CountDownLatch with 5 counts after which convey down the depend by 1 when the loading of 1 class is completed. You are able to do this by calling the countDown() technique.
Since completely different threads will take completely different instances, your most important thread can wait till all threads have been accomplished and it will probably do by checking the remaining depend by calling the getCount() technique or simply calling the CountDownLatch.await() technique, which causes the present thread to attend till the latch has counted right down to zero or the thread is interrupted.
As soon as the depend turns into zero, it will probably announce that the applying is began and able to settle for consumer connections. So, you may see how helpful CountDownLatch will be in this sort of situation.
There are lots of different concurrency utilities in JDK that can make it easier to to put in writing subtle Java functions however If you’re new to Java and wrestle to grasp multi-threading and concurrency ideas like this, you may undergo a multithreading course like Multithreading and Parallel Computing in Java course from Udemy. It is an important course to be taught the multithreading fundamentals and grow to be a greater Java developer.
1. CountDownLatch Instance in Java
Right here is the diagram as an example the purpose that how the primary thread waited till the depend reaches zero. In our instance, you may depend the entire variety of programs downloaded and print on the finish of this system.
Now, let’s examine the code to grasp the CountDownLatch a bit extra:
package deal device;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
non-public static last CountDownLatch loadingLatch = new CountDownLatch(3);
public static void most important(String args[]) {
Thread pythonCourseLoader = new Thread("PythonCourseLoader") {
@Override
public void run() {
System.out.println("Loading all Python programs from Udemy..");
System.out.println("loading accomplished for Python programs");
loadingLatch.countDown();
}
};
Thread javaCourseLoader = new Thread("JavaCourseLoader") {
@Override
public void run() {
System.out.println("Loading all Java programs from Udemy ..");
strive {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("loading accomplished for Java programs");
loadingLatch.countDown();
}
};
Thread developmentCourseLoader = new Thread("developmentCourseLoader") {
@Override
public void run() {
System.out.println("Loading all Develoment programs from Udemy ..");
strive {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("loading accomplished for growth programs");
loadingLatch.countDown();
}
};
pythonCourseLoader.begin();
javaCourseLoader.begin();
developmentCourseLoader.begin();
whereas (loadingLatch.getCount() != 0) {
}
System.out.println("all completed.");
}
}
Output:
Loading all Python programs from Udemy..
loading accomplished for Python programs
Loading all Improvement programs from Udemy ..
Loading all Java programs from Udemy ..
loading accomplished for Java programs
loading accomplished for growth programs
all completed.
On this program, now we have simply three threads. One to obtain all Python programs, the second to obtain all Java programs, and the third one to obtain all Improvement programs.
CountDownLatch loadingLatch = new CountDownLatch(3);
After that, now we have three threads, which downloads information, in our case they do not do something simply sleep for 1, 2, and three seconds.
Each time a thread completes its execution it calls the countDown() technique on the loadingLatch object.
The most important() technique retains checking for remaining counts utilizing the getCount() technique and does no matter it desires to do solely when the depend reaches zero. Although I’ve used some time loop with getCount(), you may higher use latch.await() technique for ready.
An image is alleged to be price a thousand phrases, so I attempted to make this diagram to clarify the idea to you. On this diagram you may see that our most important thread is ready on CoutnDownLatch till all thread calls the countdown and depend reaches zero, after that, it progressed additional.
Briefly, the primary thread was blocked ready for different loader thread to complete their job.
Btw, If you’re not aware of important threading ideas like wait, notify, sleep, blocking, and so on, I counsel you first undergo Full Java Masterclass to be taught them.
2. CountDownLatch – Vital Factors
Now that you realize what’s CountDownLatch in Java and the best way to use it for inter-thread communication and synchronization. It is time to revise and keep in mind some necessary factors:
1. The CountDownLatch utility or class is simply out there on JRE 1.5 or later variations.
2. You can not reuse the latch as soon as the depend reaches zero. That is the primary distinction between a CyclicBarrier and CountDownLatch, which will be reused.
3. The getCount() technique returns the present depend i.e. remaining threads that haven’t completed but.
4. A thread can wait on the latch by calling the latch.await() technique to start out progress after the remaining thread finishes their process. Btw, if you wish to be taught threading and concurrency in depth and wish to write a high-performance java software then, I counsel you undergo Java Multithreading, Concurrency, and Efficiency Optimization course to be taught extra about efficiency optimization and writing strong concurrent code in Java
5. One of many easiest use of CountDownLatch class is to block a thread till different threads have completed their jobs.
In our instance, it was the primary thread that was blocked by calling the await() technique of CountDownLatch till all loader class completed their job i.e. downloaded programs from Udemy.
That is all about the best way to use CountDownLatch in Java. It is a helpful concurrency utility that can be utilized to maintain observe of the completion of duties completed by a number of threads. If you’re writing a Java software that hundreds information from one other system earlier than beginning functioning e.g. accepting consumer connections, you should use CountDownLatch to maintain observe of obtain duties.
Thanks loads for studying this text thus far. Should you like this CountDownLatch instance in Java then please share it with your folks and colleagues. When you have any questions or suggestions then please drop a notice.
P. S. – If you’re severe to enhance your Java Multithreading and Concurrency Expertise however in search of a free course to start out with then I additionally, counsel you take a look at this superior free Java Multithreading course
on Udemy.