Thursday, April 25, 2024
HomeJavaProducer Client Drawback with Wait and Notify - Thread Instance Tutorial

Producer Client Drawback with Wait and Notify – Thread Instance Tutorial


Disclosure: This text could include affiliate hyperlinks. If you buy, we could earn a fee.

The Producer-Client Drawback is a classical concurrency downside and in reality, it is without doubt one of the strongest concurrency design patterns which is utilized in most multithreaded Java purposes. Within the final article, I’ve proven you the best way to clear up the Producer-Client downside in Java utilizing blocking Queue however one in all my readers emailed me and requested a code instance and clarification of fixing the Producer-Client downside in Java with the wait and notify methodology as properly Because it’s typically requested as one of many prime coding questions in Java. On this Java tutorial, I’ve put the code instance of the wait notify model of the sooner producer-consumer concurrency design sample. 

You’ll be able to see it is a for much longer code with specific dealing with blocking situations like when the shared queue is full and when the queue is empty which could be difficult for anybody. Since now we have changed BlockingQueue
with Vector we have to implement blocking utilizing wait
and notify
and that is why now we have launched the 
produce(int i) and devour() methodology.

If
you see I’ve stored the buyer thread slightly gradual by permitting it to sleep for 50 Milliseconds to provide a possibility to the producer to fill the queue, which helps
to know that the Producer thread can be ready when Queue is full.


By the best way, in case you are new to multithreading in Java then I additionally recommend you be part of a course like Multithreading and Parallel Computing in Java from Udemy. It is a fantastic course to be taught the multithreading fundamentals and develop into a greater Java developer.  



Java program to unravel Producer-Client Drawback in Java

Here’s a full Java program to unravel the basic producer-consumer downside within the Java
programming language. On this program, now we have used the wait and notify methodology from

java.lang.Object
class as a substitute of utilizing BlockingQueue for move management which makes implementing producer-consumer sample very easy.

Earlier than fixing the issue, let’s revisit what’s the producer-consumer downside first?

It is a classical synchronization downside that entails a fastened measurement buffer or queue which might have objects or activity added to it or faraway from it by completely different producer and shopper threads. 

The secret’s to unravel the issue in such a approach that the producer ought to wait if the queue is full and the buyer ought to wait if the queue is empty which entails inter-thread communication. 

This downside can be identified by completely different names within the technical world like a consumer-producer downside, bounded buffer downside, or a blocking queue downside. I extremely suggest you grasp this downside to enhance your concurrency expertise.

When you want extra such issues I recommend fixing the multithreading issues given in Java Multithreading for Senior Engineering Interviews on Educative. It is an interactive course that teaches you the best way to clear up classical concurrency issues like producer-consumer, eating philosophers, Barber store issues, and Uber Journey issues. 

How to solve Producer Consumer Problem with Wait and Notify - Thread Example

Now, let’s examine the code and attempt to perceive how does it work:

import java.util.Vector;
import java.util.logging.Stage;
import java.util.logging.Logger;

/**
 * Java program to unravel Producer Client downside utilizing wait and
notify

 * methodology in Java. Producer Client can be a preferred concurrency design
sample.
 *
 * @creator Javin Paul
 */

public class
ProducerConsumerSolution {

    public static void
most important(String args[]) {
        Vector sharedQueue = new Vector();
        int measurement
= 4;
        Thread prodThread = new Thread(new Producer(sharedQueue,
measurement), “Producer”);
        Thread consThread = new Thread(new Client(sharedQueue,
measurement), “Client”);
        prodThread.begin();
        consThread.begin();
    }
}

class Producer implements Runnable {

    personal ultimate Vector sharedQueue;
    personal ultimate int
SIZE;

    public Producer(Vector sharedQueue, int measurement) {
        this.sharedQueue = sharedQueue;
        this.SIZE = measurement;
    }

    @Override
    public void run() {
        for (int i =
0; i < 7; i++) {
            System.out.println(“Produced: “
+ i);
            strive
{
                produce(i);
            } catch (InterruptedException
ex) {
                Logger.getLogger(Producer.class.getName()).log(Stage.SEVERE,
null, ex);
            }

        }
    }

    personal void produce(int i) throws InterruptedException {

        //wait if the queue is
full

        whereas (sharedQueue.measurement() == SIZE) {
            synchronized
(sharedQueue)
{
                System.out.println(“The queue is full
+ Thread.currentThread().getName()

                                    + ” is ready , measurement: “ + sharedQueue.measurement());

                sharedQueue.wait();
            }
        }

        //producing component
and notify shoppers

        synchronized
(sharedQueue)
{
            sharedQueue.add(i);
            sharedQueue.notifyAll();
        }
    }
}

class Client implements Runnable {

    personal ultimate Vector sharedQueue;
    personal ultimate int
SIZE;

    public Client(Vector sharedQueue, int measurement) {
        this.sharedQueue = sharedQueue;
        this.SIZE = measurement;
    }

    @Override
    public void run() {
        whereas (true) {
            strive
{
                System.out.println(“Consumed: “
+ devour());
                Thread.sleep(50);
            } catch (InterruptedException
ex) {
                Logger.getLogger(Client.class.getName()).log(Stage.SEVERE,
null, ex);
            }

        }
    }

    personal int devour()
throws InterruptedException {
        //wait if the queue is
empty

        whereas (sharedQueue.isEmpty()) {
            synchronized
(sharedQueue)
{
                System.out.println(“The queue is empty
+ Thread.currentThread().getName()

                                    + ” is ready ,
measurement: “
+ sharedQueue.measurement());

                sharedQueue.wait();
            }
        }

        //In any other case devour
component and notify the ready producer

        synchronized
(sharedQueue)
{
            sharedQueue.notifyAll();
            return
(Integer)
sharedQueue.take away(0);
        }
    }
}

Output:
Produced: 0
The queue is empty Client is ready, measurement: 0
Produced: 1
Consumed: 0
Produced: 2
Produced: 3
Produced: 4
Produced: 5
The queue is full Producer is ready, measurement: 4
Consumed: 1
Produced: 6
The queue is full Producer is ready, measurement: 4
Consumed: 2
Consumed: 3
Consumed: 4
Consumed: 5
Consumed: 6
The queue is empty Client is ready, measurement: 0

When you have a look at the output there are a few factors which is value noting:

1. Each Producer and Client thread can run in any order, despite the fact that you have got began it does not imply that the producer will produce first after which the buyer will devour. Every time the producer will get an opportunity it retains producing till the queue is full, the identical goes with the buyer. 

2. You’ll be able to see that the Client is ready when the queue is empty and the Producer is ready when the queue is full which is the anticipated conduct. 

3. Any change to the shared object, right here sharedQueue which is a vector is going on contained in the synchronized block in order that adjustments made by one thread are seen to the opposite. Bear in mind every time a thread exit or enter a synchronized block, the reminiscence barrier is refreshed. 

That is the usual conduct of the Java reminiscence mannequin and I extremely suggest you to learn Java Concurrency in Apply – The E book at the least as soon as to be taught extra about reminiscence limitations, Java Reminiscence Mannequin, and happens-before in Java. 
Producer consumer pattern in Java using wait and notify

How to solve Producer Consumer Problem in Java with ExampleThat’s all on The right way to clear up the producer-consumer downside in Java utilizing the wait and notify methodology. I nonetheless assume that utilizing BlockingQueue to
implement producer-consumer design patterns is a lot better due to its
simplicity and concise code. On the identical time, this downside is a superb
train to know the idea of the wait and notify methodology in Java.
 Different Java Multithreading and Concurrency Articles chances are you’ll like

  • The right way to do inter-thread communication in Java utilizing wait-notify? (reply)
  • The right way to pause a Thread in Java? (resolution)
  • 5 Programs to Be taught Java Multithreading in-depth (programs)
  • Distinction between risky, synchronized, and atomic variable in Java (reply)
  • 10 Java Multithreading and Concurrency Finest Practices (article)
  • Prime 5 Books to Grasp Concurrency in Java (books)
  • Prime 50 Multithreading and Concurrency Questions in Java (questions)
  • The right way to keep away from impasse in Java? (reply)
  • Distinction between CyclicBarrier and CountDownLatch in Java? (reply)
  • Distinction between ForkJoinPool and Executor Framework in Java(reply)
  • 5 Important Abilities to Crack Java Interviews (expertise)
  • Understanding the move of information and code in Java program (reply)
  • The right way to be part of two threads in Java? (reply)
  • Distinction between Executor and ExecutorService in Java? (reply)
  • The right way to cease a Thread in Java? (reply)
  • What’s Occurs Earlier than in Java Concurrency? (reply)


Thanks loads for studying this text thus far. When you like this instance of fixing the producer-consumer downside utilizing wait and notify in Java then please share it with your folks and colleagues. When you have any questions or suggestions then please drop a be aware.

P. S. – If you’re new however what to be taught Java Multithreading and Concurrency and in search of a free course to start out with then I additionally, recommend you try this superior free Java Multithreading course on Udemy. 

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments