CountDownLatch Vs CyclicBarrier

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

11/6/23, 1:53 AM CountDownLatch in Java Concurrency Utilities | Code Pumpkin

CountDownLatch In Java Concurrency Utilities


May 5, 2017 Posted by Abhi Andhariya Core Java, Java MultiThreading

CountDownLatch in Java Concurrency is a type of synchronizer which allows one Thread to wait for one or more Threads before it starts processing.

You can implement the same functionality using wait() & Notify() mechanism but it requires lot of code and getting it write in first attempt is tricky,
With CountDownLatch it can be done in just few lines.

It was introduced in Java 5 along with other concurrent classes like CyclicBarrier, ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue within
java.util.Concurrent package.

CountDownLatch Exmaple In Java


Here is an easy example to remember its behavior: "4 employees share a common cab while leaving from office. Driver can lift the car only after all 4
take their seats in the car."

Lets implement above situation using CountDown Latch. For better understanding of this Java program, please read steps mentioned next to the program.

1
2 import java.util.concurrent.CountDownLatch;
3
4 /**
5 * CountDown Latch is useful if you want to start main processing thread once its
6 * dependency is completed as illustrated in this Example.
7 *
8 * In this example, Car can start only after all 4 employees take their seat in the car.
9 *
10 */
11 public class CarDriver{
12
13 public static void main(String args[]) {
14
15 final CountDownLatch latch = new CountDownLatch(4);
16 Thread emp1 = new Thread(new Employee("EMP 1", 1000, latch));
17 Thread emp2 = new Thread(new Employee("EMP 2", 1000, latch));
18 Thread emp3 = new Thread(new Employee("EMP 3", 1000, latch));
19 Thread emp4 = new Thread(new Employee("EMP 4", 1000, latch));
20
21 // separate threads will start moving all four employees
https://codepumpkin.com/countdownlatch-java-concurrency/ 1/5
11/6/23, 1:53 AM CountDownLatch in Java Concurrency Utilities | Code Pumpkin
22 // from their office to car parking.
23
24 emp1.start();
25 emp2.start();
26 emp3.start();
27 emp4.start();
28
29
30 // Driver should not start car until all 4 employees take their seats in the car.
31
32 try
33 {
34 // carDriver thread is waiting on CountDownLatch to finish
35 latch.await();
36 System.out.println("All employees have taken their seat, Driver started the car");
37 }
38 catch(InterruptedException ie){
39 ie.printStackTrace();
40 }
41
42 }
43
44 }
45
46 /**
47 * Employee class which will be executed by Thread using CountDownLatch.
48 */
49 class Employee implements Runnable{
50 private final String name;
51 private final int timeToReachParking;
52 private final CountDownLatch latch;
53
54 public Employee(String name, int timeToReachParking, CountDownLatch latch){
55 this.name = name;
56 this.timeToReachParking = timeToReachParking;
57 this.latch = latch;
58 }
59
60 @Override
61 public void run() {
62 try {
63 Thread.sleep(timeToReachParking);
64 } catch (InterruptedException ex) {
65 System.err.println("Error : ");
66 ex.printStackTrace();
67 }
68 System.out.println( name + " has taken his seat");
69 latch.countDown(); //reduce count of CountDownLatch by 1
70 }
71
72 }

https://codepumpkin.com/countdownlatch-java-concurrency/ 2/5
11/6/23, 1:53 AM CountDownLatch in Java Concurrency Utilities | Code Pumpkin

Output
1 EMP 4 has taken his seat
2 EMP 3 has taken his seat
3 EMP 1 has taken his seat
4 EMP 2 has taken his seat
5 All employees have taken their seat, Driver started the car

Steps To Use CountDown Latch In Your Java Program


https://codepumpkin.com/countdownlatch-java-concurrency/ 3/5
11/6/23, 1:53 AM CountDownLatch in Java Concurrency Utilities | Code Pumpkin

1. Start main thread

2. Create CountDownLatch with initial count (say count=N for N threads)

CountDownLatch class defines one constructor inside:

1 //Constructs a CountDown Latch initialized with the given count.


2 public CountDownLatch(int count) {...}

This count is essentially the number of threads, for which latch should wait. This value can be set only once, and CountDown Latch provides no other
mechanism to reset this count.

3. Create and start N threads

4. Call CountDownLatch.await() from main thread

This main thread must call, await() method immediately after starting other threads. The execution will stop on await() method till the time, other threads
complete their execution.

5. Call CountDownLatch.countDown() method on completing execution of each Thread

Other N threads must have reference of latch object, because they will need to notify the CountDown Latch object that they have completed their task. This
notification is done by method countDown(). Each invocation of method decreases the initial count set in constructor, by 1.

6. resume main thread

when all N threads have call this method, count reaches to zero, and main thread is allowed to resume its execution past await() method.

CountDown Latch Can Not Be Reused


One point to remember is CountDown Latch cannot be reused. Once the countdown reaches zero any further call to await() method won't block any thread. It
won't throw any exception either.

Points To Note

https://codepumpkin.com/countdownlatch-java-concurrency/ 4/5
11/6/23, 1:53 AM CountDownLatch in Java Concurrency Utilities | Code Pumpkin

A CountDownLatch initialized to N, using its constructor, can be used to make one (or more) thread wait until N threads have completed some action.
countDown() method is used to decrement the count, once the count reaches zero the latch is released.
await() method is used to block the thread(s) waiting for the latch to release.
CountDown Latch cannot be reused. Once the countdown reaches zero any further call to await() method won't block any thread.
There is a similar concurrency utility called CyclicBarrier, which can also be used to simulate this scenario but difference between CountDown
Latch and CyclicBarrier is that you can reuse the cyclic barrier once the barrier is broken, but you cannot reuse the CountDownLatch once count reaches
to zero. For more details on the differences between them, read our post CountDownLatch Vs CyclicBarrier | Java Concurrency Utilities
Java 7 also introduced a flexible alternative of CountDownLatch, known as Phaser. It also has number of unarrived party just like barrier and latch but
that number is flexible.

https://codepumpkin.com/countdownlatch-java-concurrency/ 5/5
11/6/23, 1:57 AM CountDownLatch Vs CyclicBarrier | Java Concurrency Utilities | Code Pumpkin

CountDownLatch Vs CyclicBarrier | Java Concurrency Utilities


May 25, 2017 Posted by Abhi Andhariya Core Java, Interview Questions, Java MultiThreading, Multithreading Interview Questions

CountDownLatch Vs CyclicBarrier : Though both are used as a synchronization aid that allows one or more threads to wait but there are certain differences
between them that you should know in order to know when one of these utilities will serve you better.

As per the java.util.concurrent API,

CountDownLatch: A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads complete.
CyclicBarrier: A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.

Here are few basic differences.

1. In CountDownLatch, only main thread waits for other threads to complete their execution, where as in CyclicBarrier, Each worker threads wait for
each other to complete their execution. Let's understand this by following Example :

CountDownLatch:
Consider a IT world scenario where manager divided modules between development teams (A and B) and he wants to assign it to QA team for testing
only when both the teams completes their task.

Here manager thread works as main thread and development team works as worker thread. Manager thread waits for development teams thread to
complete their task. Once developer teams complete their tasks, they will inform manager thread and then manager thread assign modules to QA team.

CyclicBarrier:
Consider the same scenario where manager divided modules between development teams (A and B). He goes on leave. He asked both teams to wait for
each other to complete their respective taskand once both teams are done, assign it to QA team for testing.

Here manager thread works as main thread and development team works as worker thread. Development team threads wait for other development
team threads after completing their task.

https://codepumpkin.com/countdownlatch-vs-cyclicbarrier/ 1/2
11/6/23, 1:57 AM CountDownLatch Vs CyclicBarrier | Java Concurrency Utilities | Code Pumpkin

In Other words, a CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action. Where as
if CyclicBarrier has been initialized to 3 then you should have at least 3 threads to call await().

2. Reusability :We can not reuse same CountDownLatch instance once count reaches to zero and latch is open. CyclicBarrier can be reused after all the
waiting threads are released.

3. barrierAction : A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives,
but before any threads are released.

So with CyclicBarrier you have an option to have an Action class specified in the CyclicBarrier constructor that will be run after the last thread has
called await(). This barrier action is useful for updating shared-state before any of the parties continue.

1 public CyclicBarrier(int parties, Runnable barrierAction)

CountDownLatch doesn't provide any such constructor to specify a runnable action.

Summary

COUNT DOWN LATCH CYCLIC BARRIER

1 Main threads waits for other threads to complete Each worker threads wait for each other to complete their execution
their execution.

2 We can not reuse same CountDownLatch instance CyclicBarrier can be reused by resetting Barrier, Once barrier is broken.
once count reaches to zero and latch is open.

3 No Such Action can be provided with We can provide barrierAction that is run once per barrier point, after the
CountDownLatch last thread in the party arrives, but before any threads are released.

https://codepumpkin.com/countdownlatch-vs-cyclicbarrier/ 2/2
11/6/23, 1:56 AM CyclicBarrier | Java Concurrency Utilities | Code Pumpkin

CyclicBarrier | Java Concurrency Utilities


May 25, 2017 Posted by Abhi Andhariya Core Java, Java MultiThreading

CyclicBarrier was introduced in Java 5 along with other concurrent classes like CountDownLatch, ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue
within java.util.Concurrent package.

There are scenarios in concurrent programming when you want set of threads to wait for each other at a common point until all threads in the set have
reached that common point.

The java.util.concurrent.CyclicBarrier class is a barrier that all threads must wait at, until all threads reach it, before any of the threads can continue.

The barrier is called cyclic because it can be re-used after the waiting threads are released.

https://codepumpkin.com/cyclicbarrier-java-concurrency-utilities/ 1/6
11/6/23, 1:56 AM CyclicBarrier | Java Concurrency Utilities | Code Pumpkin

You can implement the same functionality using wait() & Notify() mechanism but it requires lot of code and getting it write in first attempt is tricky,
With CyclicBarrier it can be done in just few lines.

CyclicBarrier Exmaple In Java


Here is an easy example to remember its behavior: "4 bikers have started driving from Manali to Leh. As all of them are driving at different speed, they
have decided some checkpoints in their route. After reaching to first checkpoint, everybody waits for others to reach that checkpoint. Once all 4
arrives, they will refill the petrol tanks and resume their rides and drive until their next checkpoint. "

https://codepumpkin.com/cyclicbarrier-java-concurrency-utilities/ 2/6
11/6/23, 1:56 AM CyclicBarrier | Java Concurrency Utilities | Code Pumpkin

In above example, bikers are worker threads or parties. checkpoint is barrier. Once all bikers reaches the checkpoint/barrier they will refill the petrol
(barrierAction) and reset the barrier.

Lets implement above situation using CyclicBarrier. For better understanding of this Java program, please read steps mentioned next to the program.

1 import java.util.concurrent.BrokenBarrierException;
2 import java.util.concurrent.CyclicBarrier;
3
4 public class CyclicBarrierDemo {
5
6 public static void main(String args[])
7 {
8
9 // creating CyclicBarrier (checkPoint) with
10 // 4 parties (Bikers) threads that need to call await()
11 final CyclicBarrier checkPoint = new CyclicBarrier(4, new Runnable(){
12 @Override
13 public void run(){
14 //This task will be executed once all biker threads will reach barrier
15 System.out.println("\nAll bikers have arrived to checkpoint. Lets refill the petrol\n");
16 }
17 });
18
19 //starting each of thread
20 Thread biker1 = new Thread(new Biker(checkPoint), "Biker Thread 1");
21 Thread biker2 = new Thread(new Biker(checkPoint), "Biker Thread 2");
22 Thread biker3 = new Thread(new Biker(checkPoint), "Biker Thread 3");
23 Thread biker4 = new Thread(new Biker(checkPoint), "Biker Thread 4");
24
25 biker1.start();
26 biker2.start();
27 biker3.start();
28 biker4.start();
29
30
31 }
32 }
33
34 class Biker implements Runnable
35 {
36
37 private CyclicBarrier checkPoint;
38
39 public Biker(CyclicBarrier checkPoint) {
40 this.checkPoint = checkPoint;
41 }
42
43 // Code to be executed by each biker
44 @Override

https://codepumpkin.com/cyclicbarrier-java-concurrency-utilities/ 3/6
11/6/23, 1:56 AM CyclicBarrier | Java Concurrency Utilities | Code Pumpkin
45 public void run()
46 {
47 try
48 {
49 System.out.println(Thread.currentThread().getName() + " has left Manali");
50
51 checkPoint.await();
52 System.out.println(Thread.currentThread().getName() + " has left the first checkpoint / barrier");
53
54 checkPoint.await();
55 System.out.println(Thread.currentThread().getName() + " has left the second checkpoint / barrier");
56
57 checkPoint.await();
58 System.out.println(Thread.currentThread().getName() + " has reached Leh");
59
60 }
61 catch (InterruptedException | BrokenBarrierException ex)
62 {
63 ex.printStackTrace();
64 }
65 }
66 }

Output
1 Biker Thread 1 has left Manali
2 Biker Thread 3 has left Manali
3 Biker Thread 2 has left Manali
4 Biker Thread 4 has left Manali
5
6 All bikers have arrived to checkpoint. Lets refill the petrol
7
8 Biker Thread 4 has left the first checkpoint / barrier
9 Biker Thread 1 has left the first checkpoint / barrier
10 Biker Thread 3 has left the first checkpoint / barrier
11 Biker Thread 2 has left the first checkpoint / barrier
12
13 All bikers have arrived to checkpoint. Lets refill the petrol
14
15 Biker Thread 2 has left the second checkpoint / barrier
16 Biker Thread 4 has left the second checkpoint / barrier
17 Biker Thread 3 has left the second checkpoint / barrier
18 Biker Thread 1 has left the second checkpoint / barrier
19
20 All bikers have arrived to checkpoint. Lets refill the petrol
21
22 Biker Thread 1 has reached Leh
23 Biker Thread 2 has reached Leh
24 Biker Thread 4 has reached Leh
25 Biker Thread 3 has reached Leh

https://codepumpkin.com/cyclicbarrier-java-concurrency-utilities/ 4/6
11/6/23, 1:56 AM CyclicBarrier | Java Concurrency Utilities | Code Pumpkin

Steps To Use CyclicBarrier In Your Java Program


1. Start main thread

2. Create CyclicBarrier object

CyclicBarrier class has following two constructors. Both of them create a new CyclicBarrier object with the total number of parties / threads which wait for
each other after reaching the Barrier.

1 CyclicBarrier(int parties);
2
3 CyclicBarrier(int parties, Runnable barrierAction);

Here parties parameter signifies the number of threads that must invoke await() after reaching the barrier i.e. Biker threads

barrierAction specifies a thread that will be executed when the barrier is reached i.e. Refilling Petrol

3. Create and start N threads

4. Call await() method at each barrier/checkpoint in thread's run() method.

When each thread reaches the barrier (checkpoint), call await() method on the CyclicBarrier object. This will suspend the thread until all the thread also call
the await() method on the same CyclicBarrier object.

Once all the specified threads have called await() method, they can resume operation.

await() method has following two forms :

1 public int await() throws InterruptedException, BrokenBarrierException


2
3 public int await(long timeout, TimeUnit unit)
4 throws InterruptedException, BrokenBarrierException, TimeoutException

In the second form, it waits until all parties have invoked await() on this barrier, or the specified waiting time elapses.

await() method returns int which is the arrival index of the current thread.

https://codepumpkin.com/cyclicbarrier-java-concurrency-utilities/ 5/6
11/6/23, 1:56 AM CyclicBarrier | Java Concurrency Utilities | Code Pumpkin

If the current thread is not the last to arrive then it is disabled for thread scheduling purposes and lies dormant until one of the following things happens:

The last thread arrives; or


The specified timeout elapses; (In case of second form) or
Some other thread interrupts the current thread; or
Some other thread interrupts one of the other waiting threads; or
Some other thread times out while waiting for barrier; or
Some other thread invokes reset() on this barrier.

await() method throws two exceptions:

1. InterruptedException – if the current thread was interrupted while waiting


2. BrokenBarrierException If a thread leaves a barrier point prematurely because of interruption, failure, or timeout, all other threads waiting at that
barrier point will also leave abnormally via BrokenBarrierException

Though both CountDownLatch and CyclicBarrier are used as a synchronization aid that allows one or more threads to wait but there are certain differences
between them that you should know. Here is our post CountDownLatch Vs CyclicBarrier | Java Concurrency Utilities where we have explained each difference
in detail

https://codepumpkin.com/cyclicbarrier-java-concurrency-utilities/ 6/6
11/6/23, 1:58 AM interrupt(), interrupted() and isInterrupted() in Java Multithreading | Code Pumpkin

Interrupt(), Interrupted() And IsInterrupted() In Java Multithreading


May 13, 2017 Posted by Abhi Andhariya
Core Java, Interview Questions, Java MultiThreading, Multithreading Interview Questions

In this post, we will understand about interrupt(), interrupted() and isInterrupted() methods in Java Multithreading.

If you are interested in reading more about interruption mechanism you can look into our post InterruptedException in Java Multithreading.

In Java, thread starts its execution when we call start() method on Thread object. It internally calls overridden run() method. Thread is said to be
terminated when execution of run() method completes.

Shutting down thread forcefully means stopping the execution of thread, even if it has not yet completed execution of run() method.

In real-time applications, you may come across a scenario where you need to use multiple threads to complete the task and there may be a requirement to
forcefully shutdown all your threads on triggering of some event.

For example, You are downloading 50 files from server with 5 different threads, 10 files using each thread. Now lets say you want to provide a button to
cancel the download. How you will do that? You need to shutdown all five threads.

Let's start with this code:

1 while (true) {
2 // Do Nothing
3 }

It keeps on executing infinitely. It will only stop until JVM will stop or we will kill the process by hitting Ctrl + C.

Lets put this infinite loop into thread:

1 Thread loop = new Thread(


2 new Runnable() {
3 @Override
4 public void run() {
5 while (true) {
6 // Do Nothing

https://codepumpkin.com/interrupt-interrupted-isinterrupted-java-multithreading/ 1/3
11/6/23, 1:58 AM interrupt(), interrupted() and isInterrupted() in Java Multithreading | Code Pumpkin
7 }
8 }
9 }
10 );
11 loop.start();
12 // Now how do we stop it?

How Do We Stop A Thread When We Need It To Be Stopped?


If we are using JDK 1.0 , we can call Thread's deprecated method stop() to terminate it. Using stop() is incredibly dangerous, as it will kill your thread even
if it is in the middle of something important. There is no way to protect yourself, so if you spot code that uses stop(), you should frown.

How do we shutdown a thread cleanly?

In Java, starting a threads is easy, but shutting them down require a lot of attention and efforts.

Here is how it is designed in Java. There is a flag called Interrupt status flag in every java thread that we can set from the outside i.e. parent or main thread.
And the thread may check it occasionally and stops its execution. Voluntarily..!! Here is how:

1 Thread loop = new Thread(


2 new Runnable() {
3 @Override
4 public void run() {
5 while (true) {
6 if (Thread.interrupted()) {
7 break;
8 }
9 // Continue to do nothing
10 }
11 }
12 }
13 );
14 loop.start();
15 loop.interrupt();

There are two methods that are used in this example.

1. interrupt() : When we call loop.interrupt(), an Interrupt status flag is set to true.


2. interrupted() : It is static method and checks the interrupt status flag of current thread. When we call interrupted(), the flag is returned and
immediately set to false.

Thus, if we never call Thread.interrupted() inside the run method and don't exit when the flag is true, nobody will be able to stop us.

https://codepumpkin.com/interrupt-interrupted-isinterrupted-java-multithreading/ 2/3
11/6/23, 1:58 AM interrupt(), interrupted() and isInterrupted() in Java Multithreading | Code Pumpkin

In other words, parent thread will ask child thread to stop by calling interrupt()method, but child thread will just ignore these calls.

As per the tutorial on concurrency in Java Documentation

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a
thread responds to an interrupt, but it is very common for the thread to terminate

isInterrupted() : There is one more method about which you should know is isInterrupted(). It is an instance method which returns the value
of Interrupt status flag of a Thread object for which it is called on.

Interrupted() Vs IsInterrupted()

interrupted() isInterrupted()

1 The interrupted() is a static method in Thread class that determines if the current The isInterrupted() is
thread has been interrupted. an instance method that tests if this
thread instance has been interrupted.

1 "The interrupted status of the thread is cleared by this method". Therefore, if "The interrupted status of the thread
a thread was interrupted, calling interrupted() once would return true, while a is unaffected by this method".
second call to it would return false until the current thread is interrupted again.

I strongly recommend you to also read about InterruptedException in Java Multithreading to know more about interruption mechanism.

https://codepumpkin.com/interrupt-interrupted-isinterrupted-java-multithreading/ 3/3
11/6/23, 1:58 AM InterruptedException in Java Multithreading | Code Pumpkin

InterruptedException In Java Multithreading


May 13, 2017 Posted by Abhi Andhariya
Core Java, Interview Questions, Java MultiThreading, Multithreading Interview Questions

InterruptedException is thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the
activity.

Before reading this article, I recommend you to go through my article interrupt(), interrupted() and isInterrupted() in Java Multithreading.

There are some methods in JDK that check the Interrupt status flag for us and throw InterruptedException, if it is set. For example, All the blocking
methods i.e. wait(), sleep(), join().

I have not seen many programmers handle InterruptedException correctly. Most of the time, programmers view them as an irritating checked exceptions
that they have to catch.

Just to ignore IDE's compilation error , they wrap sleep() or wait() method call with try-catch block having InterruptedException.

The Question arises here is, why all blocking method throws InterruptedException? Let's understand this by following example. Here is the
implementation of my thread's run() method.

1 @Override
2 public void run()
3 {
4 while (true)
5 {
6 if (Thread.interrupted())
7 {
8 break;
9 }
10
11 // Case 1 : code to be executed before sleep method call
12
13 try
14 {
15 sleep(10_000_000); // Case 2 : sleep for 10,000 seconds
16 }
17 catch(InterruptedException ie)

https://codepumpkin.com/interruptedexception-java-multithreading/ 1/5
11/6/23, 1:58 AM InterruptedException in Java Multithreading | Code Pumpkin
18 {
19 // Clean up code
20 }
21
22 // Case 3 : code to be executed after sleep method call
23 }
24
25 // Clean up code
26 }

In above code, my run() method checks for Thread.interrupted() in the starting of each loop iteration. If Interrupt status flag is true, it will break the
while loop. else it will complete that iteration.

I have also highlighted three execution points. Let's understand what will happen when parent thread call interrupt() method and execution has reached
to any one of these three execution points.

case 3 :

1. Cursor has reached to line 22 and its executing code after the sleep() method.
2. At the same time, main thread calls interrupt() method.
3. Cursor will complete that iteration and will start next iteration.
4. Cursor will enter if block as Thread.interrupted() will return true. It will break the while loop.
5. Cursor will execute clean up code written on line 25.

case 2 :

1. Cursor has reached to line 15 and its executing code of native sleep() method.
2. At the same time, main thread calls interrupt() method.
3. sleep() method throws InterruptedException. Imagine if there is no mechanism like InterruptedException . Even though your parent thread has
called interrupt method, child thread can't be stopped as it will sleep for 10,000 seconds (around 3 hours). To overcome such situations sleep() method
internally keeps checking for Interrupt status flag.

This is how the method Thread.sleep() may have designed internally in java.

1 public static void sleep(long millis) throws InterruptedException


2 {

https://codepumpkin.com/interruptedexception-java-multithreading/ 2/5
11/6/23, 1:58 AM InterruptedException in Java Multithreading | Code Pumpkin
3 while (/* still waiting for millis to become zero */)
4 {
5 if (Thread.interrupted())
6 {
7 throw new InterruptedException();
8 }
9 // Keep waiting
10 }
11 }

Note : Thread.sleep()is a native method of Thread class. Above code snippet is just to show high level implementation overview of it.

4. Cursor will move to catch block and execute clean up code written on line 19.

case 1 :

1. Cursor has reached to line 11 and its executing code before the sleep() method.
2. At the same time, main thread calls interrupt() method.
3. Cursor will complete executing code before thesleep() method and enters sleep() method.
4. sleep() method throws InterruptedException.
5. Cursor will move to catch ​block and execute clean up code written on line 19.

Real Time Usage Of InterruptedException


Main reason for throwing InterruptedException is to unblock (for some reason) a thread that is blocked and execute cleanup code. We can take an
example of application shutdown.

When you shutdown your application, if you have threads waiting on let say sleep() or wait() , if you do not tell them that you are shutting down they will
continue to wait(). If those threads are not daemon threads, then your application won't shutdown.

So, when thread gets interrupted during sleep(), you have to check the conditions and handle the situation. In case of shutdown, you have to check
your shutdown flag and eventually do the clean-up work and let the thread go.

What will happen if developer swallows the InterruptedException and do nothing inside catch block?

1 try {

https://codepumpkin.com/interruptedexception-java-multithreading/ 3/5
11/6/23, 1:58 AM InterruptedException in Java Multithreading | Code Pumpkin
2 Thread.sleep(100);
3 } catch (InterruptedException ex) {
4 }

Remember, Thread.interrupted() not only returns the flag but also sets it to false. Thus, once InterruptedException is thrown, the flag is reset. The
parent thread no longer knows anything about the interruption request sent by the owner.

The owner of the thread asked us to stop, Thread.sleep() detected that request, removed it, and threw InterruptedException. If you
call Thread.sleep(), again, it will not know anything about that interruption request and will not throw anything.

It's very important not to lose that InterruptedException. We can't just swallow it and move on. That would be a severe violation of the entire Java multi-
threading idea. Our owner (the owner of our thread) is asking us to stop, and we just ignore it. That's a very bad idea.

This is what most of us are doing with InterruptedException:

1 try {
2 Thread.sleep(100);
3 } catch (InterruptedException ex) {
4 throw new RuntimeException(ex);
5 }

It looks logical, but it doesn't guarantee that the higher level will actually stop everything and exit. They may just catch a runtime exception there, and the
thread will remain alive. The owner of the thread will be disappointed.

We have to inform the higher level that we just caught an interruption request. We can't just throw a runtime exception. Such behavior would be
too irresponsible. The entire thread received an interruption request, and we merely swallow it and convert it into a RuntimeException. We can't treat such a
serious situation so loosely.

This is what we have to do:

1 try {
2 Thread.sleep(100);
3 } catch (InterruptedException ex) {
4 Thread.currentThread().interrupt(); // Here!
5 throw new RuntimeException(ex);
6 }

We're setting the flag back to true!

https://codepumpkin.com/interruptedexception-java-multithreading/ 4/5
11/6/23, 1:58 AM InterruptedException in Java Multithreading | Code Pumpkin

Now, nobody will blame us for having an irresponsible attitude toward a valuable flag. We found it in true status, cleared it, set it back to true, and threw a
runtime exception. What happens next, we don't care.

https://codepumpkin.com/interruptedexception-java-multithreading/ 5/5
11/6/23, 2:00 AM Producer Consumer Design Pattern using BlockingQueue | Code Pumpkin

Producer Consumer Design Pattern Using BlockingQueue


April 5, 2017 Posted by Abhi Andhariya Core Java, Design Patterns, Java MultiThreading

Producer Consumer Problem is a classical concurrency problem. In fact it is one of the concurrency design pattern.

This article is continuation of my post Producer Consumer Design Pattern in which I have explained basic idea, real life example, uses and benefits of
Producer Consumer Design Pattern.

Producer Consumer Design Patter can be implemented using following two approaces.

1. By using wait(), notify() and notifyAll() methods


2. By using BlockingQueue

In this post, I will explain implementation using Blocking Queue. Before reading this article, I recommend you to go throgh my article Producer Consumer
Design Pattern using wait() and notify(). It will help you to understand why BlockingQueue is more preferable while implementing Producer Consumer
Design Pattern.

In first approach we use wait() and notify() method to communicate between Producer and Consumer thread and blocking each of them on individual
condition like full queue and empty queue.

With introduction of BlockingQueue Data Structure in Java 5, its now much simpler to implement Producer Consumer Design Pattern
as BlockingQueue provides this control implicitly by introducing blocking methods put() and take().

put(E e): This method is used to insert elements to the queue. If the queue is full, it waits for the space to be available.
E take(): This method retrieves and remove the element from the head of the queue. If queue is empty it waits for the element to be available.

Now you don't require to use wait and notify to communicate between Producer and Consumer.

https://codepumpkin.com/producer-consumer-using-blockingqueue/ 1/4
11/6/23, 2:00 AM Producer Consumer Design Pattern using BlockingQueue | Code Pumpkin

Java provides several BlockingQueue implementations such


as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc.

While implementing producer consumer problem, we will use LinkedBlockingQueue implementation.

Understanding Java Program

In this program, we have two threads named PRODUCER and CONSUMER, which are instance of Producer and Consumer class respectively. Both of these
class implements Runnable interface.

The logic of what producer and the consumer should do is written in their respective run() method.

Main thread starts both PRODUCER and CONSUMER threads and also create an object of LinkedBlockingQueue class i.e. sharedQ to share as Queue
between them.

1 /**
2 * Simple Java Program to test Producer Consumer Design Pattern
3 * using BlockingQueue
4 *
5 */
6 public class ProducerConsumerBQTest {
7
8 public static void main(String[] args) throws InterruptedException {
9
10 BlockingQueue sharedQ = new LinkedBlockingQueue();
11
12
13 Thread consumerThread = new Thread(new ConsumerBQ(sharedQ), "CONSUMER");
14 Thread producerThread = new Thread(new ProducerBQ(sharedQ), "PRODUCER");
15
16 producerThread.start();
17 consumerThread.start();
18
19 }
20
21 }

Producer runs in an infinite loop and keeps inserting random integer value from 1 to 100 into sharedQ until the queue is full.

Unlike wait() and notify() implentation, here we don't need to explicity check the size of the sharedQ.

https://codepumpkin.com/producer-consumer-using-blockingqueue/ 2/4
11/6/23, 2:00 AM Producer Consumer Design Pattern using BlockingQueue | Code Pumpkin

Also we don't need to write any synchronized block as all BlockingQueue implementations are thread-safe, all queuing methods are atomic in nature and
use internal locks or other forms of concurrency control.

1 /**
2 * Producer Thread will keep producing values for Consumer.
3 *
4 * It will use put() method of BlockingQueue to add values
5 * in sharedQ
6 *
7 */
8 class ProducerBQ implements Runnable
9 {
10 private final BlockingQueue sharedQ;
11
12 public ProducerBQ(BlockingQueue sharedQ)
13 {
14 this.sharedQ = sharedQ;
15 }
16
17 @Override
18 public void run(){
19
20 while(true)
21 {
22 try
23 {
24 Random random = new Random();
25 int number = random.nextInt(100);
26 System.out.println("Producing value " + number);
27 sharedQ.put(number);
28 }
29 catch(InterruptedException ie)
30 {
31 System.err.println("Error :: " + ie);
32 }
33 }
34 }
35 }

Similarly Consumer runs in an infinite loop and keeps consuming integers from sharedQ until the queue is empty.

1 /**
2 * Consumer Thread will consumer values form shared queue.
3 *
4 * It uses take method of BlockingQueue
5 *

https://codepumpkin.com/producer-consumer-using-blockingqueue/ 3/4
11/6/23, 2:00 AM Producer Consumer Design Pattern using BlockingQueue | Code Pumpkin
6 *
7 */
8 class ConsumerBQ implements Runnable
9 {
10 private final BlockingQueue sharedQ;
11
12 public ConsumerBQ(BlockingQueue sharedQ)
13 {
14 this.sharedQ = sharedQ;
15 }
16
17 @Override
18 public void run(){
19
20 while(true)
21 {
22 try
23 {
24
25 System.out.println("Consumed value " + sharedQ.take());
26
27 }
28 catch(InterruptedException ie)
29 {
30 System.err.println("Error :: " + ie);
31 }
32 }
33 }
34 }

Download Complete Java Program »

That's all

https://codepumpkin.com/producer-consumer-using-blockingqueue/ 4/4

You might also like