Skip to main content

Implementing the Producer Consumer Pattern Using Wait and Notify in Java

Below are the conditions for producer consumer pattern. We need to ensure that the thread should not be blocked either if the buffer is empty or full. This is achieved by calling wait() and notify() method on the lock object which is used to synchronized the block of code. Please note that it is important for both threads to synchronize on the same monitor / lock object.
  • A producer produces values inside a buffer.
  • A consumer consumes the values from this buffer.
  • The buffer can be empty or full.
  • Producer and consumer runs in their own thread.

Note: wait() and notify() should not be called outside the synchronized code block

Below is the example code :

package com.refermynotes;

public class ProducerConsumerExample {
public static int[] buffer;
public static Object lock = new Object();
public static int count;

static class Producer{
public void produce(){
synchronized (lock) {
if(isFull(buffer)){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Produced: "+count);
buffer[count++] = 1;
lock.notifyAll();
}
}
}

static class Consumer{
public void consume(){
synchronized(lock){
if(isEmpty()){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer[--count] = 0;
System.out.println("Consumed: "+count);
lock.notifyAll();
}
}
}

private static boolean isEmpty() {
return count == 0;
}
private static boolean isFull(int[] buffer) {
return count == buffer.length;
}

public static void main(String[] args) {
buffer = new int[50];
count = 0;
final Producer p = new Producer();
final Consumer c = new Consumer();

Runnable producerTask = new Runnable() {
@Override
public void run() {
for(int i =0; i<100 font="" i="">
p.produce();
}
System.out.println("Done Producing");
}
};

Runnable consumerTask = new Runnable() {
@Override
public void run() {
for(int i =0; i<100 font="" i="">
c.consume();
}
System.out.println("Done Consuming");
}
};

Thread producerThread = new Thread(producerTask);
Thread consumerThread = new Thread(consumerTask);

producerThread.start();
consumerThread.start();

try {
producerThread.join();
consumerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Remaining :"+count);

}
}

Comments

Popular posts from this blog

Optimal Binary Search using Dynamic Programming

An optimal binary search tree is a binary search tree for which the nodes are arranged on levels such that the tree cost is minimum. If the probabilities of searching for elements of a set are known from accumulated data from past searches, then Binary Search Tree (BST) should be such that the average number of comparisons in a search should be minimum. eg. Lets the elements to be searched are A, B, C, D and probabilities of searching these items are 0.1, 0.2, 0.4 and 0.3 respectively. Lets consider 2 out of 14 possible BST containing these keys. Figure 1 Figure 2 Average number of comparison is calculated as sum of level*probability(key element) for each element of the tree. Lets the level of tree start from 1. Therefore, for figure 1 -     Average number of comparison = 1*0.1 +2*0.2 +3*0.4 +4*0.3  = 2.9                                  ...

Important points on Classes and Methods in Java as per Java Language Specification

Class Declarations: A class declaration specifies a new named reference type. There are two kinds of class declarations: normal class declarations and enum declarations. It is a compile-time error if a class has the same simple name as any of its enclosing classes or interfaces. Class Modifiers: A class declaration may include class modifiers. The access modifier public pertains only to top level classes and member classes, not to local classes or anonymous classes. The access modifiers protected and private pertain only to member classes within a directly enclosing class declaration. The modifier static pertains only to member classes, not to top level or local or anonymous classes. It is a compile-time error if the same keyword appears more than once as a modifier for a class declaration. abstract Classes: An abstract class is a class that is incomplete, or to be considered incomplete. It is a compile-time error if an attempt is made to create an instance o...

Web Service Explorer (An Amazing tool in eclipse IDE)

Web Service Explorer (An Amazing tool in eclipse IDE) Developer or user who wants to use the web-service has to consume the web-service and invoke the method of the service he/she wants to. Thus there are many potential ways to test the we-service exposed. • write a CICS program that invokes the Web Service • consume the WSDL and make a client project in eclipse IDE or My-Eclipse and invoke the service • generate a Java program using Rational Application Developer (RAD) or WebSphere Developer for  zSeries (WDz), • use the debugger that comes with WDz, • use the supplied Web Services Explorer that comes with RAD and WDz, • use the TCP/IP Monitor that comes with RAD and WDz, or a combination of these. Apart from these, one method to test the web-service on the ease using the web service explorer tool available in eclipse IDE. For the tutorial of how to use visit the below official link of tutorial. http://www.eclipse.org/webtools/jst/components/ws/M4/tu...