Tuesday, May 7, 2024
HomeJavaJava CyclicBarrier Instance for Rookies

Java CyclicBarrier Instance for Rookies [Multithreading Tutorial]


That is the second a part of my concurrency tutorial, within the first half, you have got realized use CountDownLatch and on this half, you’ll be taught use CyclicBarrier class in Java. CyclicBarrier is one other concurrency utility launched in Java 5 which is used when a lot of threads (also called events) need to look forward to one another at a standard level, also called the barrier earlier than beginning processing once more. It is just like the CountDownLatch however as a substitute of calling countDown() every thread calls await() and when the final thread calls await() which indicators that it has reached the barrier, all threads began processing once more, also called a barrier is damaged. 

You should utilize CyclicBarrier wherever you need to use CountDownLatch, however the reverse will not be attainable as a result of you cannot reuse the latch as soon as the depend reaches zero. Among the widespread usages of CyclicBarrier is in writing a unit check for the concurrent program, to simulate concurrency in a check class, or calculating the ultimate end result after a person activity has been accomplished.

On this tutorial, I’ll present you an instance of how 4 employee thread waits for others earlier than beginning once more. As I informed within the earlier article, concurrency is difficult to grasp, typically even when you learn a few articles on one subject, you do not get what you might be searching for. If you happen to perceive how and the place to make use of CountDownLatch and CyclicBarrier, then solely you’ll really feel assured.

Books are additionally good for mastering concurrency, and one e book, particularly, may be very helpful to be taught multithreading and concurrency in Java. You guessed it proper, I’m speaking about Java Concurrency in Follow by Brian Goetz, I strongly suggest this e book to anybody who severely desires to grasp threading and concurrency in Java. If you cannot get first hand, get a second hand one, if you cannot purchase then lend it from the library however in case you are critical about Java concurrency, it’s best to learn it.

CyclicBarrier Instance in Java

You simply can not perceive concurrency with out an instance, seeing is believing right here. It is troublesome to grasp phrases like employee thread, events, ready for one another at a degree, till you see it stay in motion. On this program, now we have 4 employee threads and one fundamental thread, which is working your fundamental methodology. 

Now we have an object of CyclicBarrier, which is initialized with events = 4, the argument we handed within the CyclicBarrier constructor is nothing however the variety of events, which is definitely the variety of threads to cease on the barrier.

The barrier won’t be damaged till all events have arrived. A celebration (thread) is alleged to have arrived with its name barrier.await() methodology.

In our instance setup, now we have given every employee thread a unique identify, ranging from PARTY-1 to PARTY-4 simply to have a significant output. Now we have handed the identical occasion of the cyclic barrier to every thread. If you happen to have a look at their Runnable implementation, you’ll find that every social gathering sleeps for some seconds after which name await() methodology on the barrier.

How to use CyclicBarrier in Java

The sleep is launched so that each thread calls the barrier methodology after a while.  Sleep time can be in rising order, which implies PARTY-4 ought to be the final one to name await. In order per our idea, each thread (social gathering) ought to wait after calling await() till the final thread (PARTY-4) calls the await() methodology, after that each thread ought to get up and begin processing.

After all, they should compete for CPU and they’re going to begin working as soon as they received the CPU from the thread scheduler, however what’s extra vital is that after the barrier is damaged, every thread (social gathering) turns into eligible for scheduling. By the best way, you may reuse the barrier even after it is damaged that is the place CyclicBarrier is totally different than CountDownLatch.

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Java Program to reveal  use CyclicBarrier, 
 * Its used when variety of threads
 * wants to attend for one another earlier than beginning once more.
 * 
 * @writer Javin Paul
 */
public class HelloHP {

    public static void fundamental(String args[]) throws InterruptedException,
                                                  BrokenBarrierException {
        
        CyclicBarrier barrier = new CyclicBarrier(4);
        Get together first = new Get together(1000, barrier, "PARTY-1");
        Get together second = new Get together(2000, barrier, "PARTY-2");
        Get together third = new Get together(3000, barrier, "PARTY-3");
        Get together fourth = new Get together(4000, barrier, "PARTY-4");
        
        first.begin();
        second.begin();
        third.begin();
        fourth.begin();
        
        System.out.println(Thread.currentThread().getName() + " has completed");

    }

}

class Get together extends Thread {
    non-public int length;
    non-public CyclicBarrier barrier;

    public Get together(int length, CyclicBarrier barrier, String identify) {
        tremendous(identify);
        this.length = length;
        this.barrier = barrier;
    }

    @Override
    public void run() {
        strive {
            Thread.sleep(length);
            System.out.println(Thread.currentThread().getName() 
                                + " is asking await()");
            barrier.await();
            System.out.println(Thread.currentThread().getName() 
                                + " has began working once more");
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}

Output
fundamental has completed
PARTY-1 is asking await()
PARTY-2 is asking await()
PARTY-3 is asking await()
PARTY-4 is asking await()
PARTY-4 has began working once more
PARTY-1 has began working once more
PARTY-2 has began working once more
PARTY-3 has began working once more

If you happen to have a look at the output is strictly matches our idea. Every employee thread (PARTY 1 – 3) calls the await() methodology after which they cease processing till PARTY-4 comes and name await() methodology, after that each thread will get a wake-up name and began execution once more, relying upon when they’re scheduled by Java thread scheduler.

That is how CyclicBarrier class works. You possibly can nonetheless reuse the barrier object and if a thread calls a barrier.await() once more, it’ll look forward to a 4 employee thread earlier than it will get a wake-up name. 

By the best way,  If the barrier is damaged earlier than a thread calls await() then this methodology will throw BrokenBarrierException. You may also see these free Java programming programs to be taught important Java ideas like these higher-level concurrency utilities in Java.

When to make use of CyclicBarrier in Java Program

It’s a very helpful class and has a number of sensible makes use of. You should utilize this to carry out the ultimate activity as soon as particular person duties are accomplished. You should utilize it to put in writing some unit assessments to test some variants as effectively. Bear in mind you may reuse the barrier versus latching.  

On a facet observe, this CyclicBarrier instance can be a great instance of catch a number of exceptions in a single catch block in Java, a characteristic launched in JDK 1.7. You possibly can see that now we have two unrelated exceptions InterruptedException and BrokenBarrierException, however now we have caught them in the identical catch block, due to this characteristic, this code requires Java 7 to run. I
f you aren’t utilizing JDK 7 then simply use two catch blocks as a substitute of 1. You may also see these Java Concurrency programs to be taught extra about CountDownLatch, CyclicBarier, Section, CompleteableFuture, and different concurrency utilities in Java. 

Java CyclicBarrier Example

That is all about use CyclicBarrier in Java. On this CyclicBarrier Instance, you haven’t solely realized use CyclicBarrier but additionally when to make use of it. You must use it when one thread wants to attend for a hard and fast variety of threads earlier than beginning an occasion e.g. Get together. You should utilize CyclicBarrier to put in writing concurrency unit assessments and implement generic algorithms in Java.

Different Java Multithreading and Concurrency Articles chances are you’ll like

  • The Java Developer RoadMap (roadmap)
  • What’s occurs earlier than in Java Reminiscence mannequin? (reply)
  • 10 Programs to Study Java Multithreading in-depth (programs)
  • Distinction between atomic, synchronized and risky in Java (reply)
  • 6 Concurrency Books Java developer can learn (books)
  • 10 Tricks to change into a greater Java Developer (suggestions)
  • Distinction between Cyclic Barrier and CountDownLatch in Java? (reply)
  • Prime 5 Books to Grasp Concurrency in Java (books)
  • 10 Java Multithreading and Concurrency Finest Practices (article)
  • Understanding the movement of information and code in Java program (reply
  • 10 Superior books for Skilled Programmers (books)
  • Prime 5 expertise to Crack Coding interviews (article)
  • Is Java Concurrency in Follow nonetheless legitimate? (reply)
  • 10 Superior Core Java Programs for Skilled Programmers (programs)

Thanks for studying this text so for. If you happen to just like the Java
Concurrency tutorial, then please share it with your folks and
colleagues. You probably have any questions or suggestions, then please drop a
observe.

P. S. – In case you are searching for a free Java multithreading course to the grasp thread ideas then I additionally counsel you take a look at this Java Multithreading free course on Udemy. It is fully free and all you want is a free Udemy account to hitch this course.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments