×

Bounded buffer problem in Java

The Bounded buffer Problem can also be called a Producer consumer problem. The problem covers two processes—the producer and the consumer—that share a single, fixed-size buffer that serves as a queue.

  • Data generation, buffering, and restarting are all tasks performed by the producer.
  • The consumer simultaneously consumes the data (i.e., removed from the buffer), one piece at a time.

The producer must either sleep or destroy data when the buffer is full. When a consumer later takes an item out of the buffer, the producer is notified, and the buffer is once more filled. In the same way, if the consumer detects that the buffer is empty, it can nod off. The consumer is awakened when the producer inserts data into the buffer to find significance.

A poor response can leave both processes in a sleeping state, unable to move on.

Bounded buffer problem in Java

Approach

  • A LinkedList list is used to store the queue of open jobs.
  • A variable capacity to determine whether the waiting list is full or not
  • a way to regulate the addition to and removal from this list so that we don't add to it if it is already full or remove it if it is already empty.

Filename: Threadex.java

// Java program to implement the solution of the producer
// consumer problem.


import java.util.LinkedList;


public class Threadex {
	public static void main(String[] args)
		throws InterruptedException
	{
		// Object of a class that has both produce()
		// and consume() methods
		final PC pc = new PC();


		// Create a producer thread
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run()
			{
				try {
					pc.produce();
				}
				catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});


		// Create a consumer thread
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run()
			{
				try {
					pc.consume();
				}
				catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});


		// Start both threads
		t1.start();
		t2.start();
		// t1 finishes before t2
		t1.join();
		t2.join();
	}
	// This class has a list, producer (adds items to list
	// and consumer (removes items).
	public static class PC {
		// Create a list shared by the producer and consumer
		// Size of the list is 2.
		LinkedList<Integer> list = new LinkedList<>();
		int capacity = 2;
		// Function called by producer thread
		public void produce() throws InterruptedException
		{
			int value = 0;
			while (true) {
				synchronized (this)
				{
					// producer thread waits while the list
					// is full
					while (list.size() == capacity)
						wait();
					System.out.println("Producer produced-"	+ value);
					// to insert the jobs in the list
					list.add(value++);
					// notifies the consumer thread that
					// now it can start consuming
					notify();
					// makes the working of the program easier
					// to understand
					Thread.sleep(1000);
				}
			}
		}


		// Function called by the consumer thread
		public void consume() throws InterruptedException
		{
			while (true) {
				synchronized (this)
				{
					// consumer thread waits while the list
					// is empty
					while (list.size() == 0)
						wait();
					// to retrieve the first job in the list
					int val = list.removeFirst();
					System.out.println("Consumer consumed-“,+ val);
					// Wake up producer thread
					notify();
					// and sleep
					Thread.sleep(1000);
				}
			}
		}
	}
}

Output

Producer produced-0
Producer produced-1
The Consumer consumed-0
The Consumer consumed-1
Producer produced-2

Important points

  • To ensure that the producer does not produce unless the list is full, a linked list of tasks and a capability of the list are introduced to the PC class (a class that includes both produce and consumption methods).
  • The initial value for the Producer class is 0.
  • We also have an endless outer loop that we can use to add values to the list. Only one producer or consumer thread may be active at once because of the synchronised block inside this loop.
  • The production threads give up the fundamental lock on the PC and enter the waiting state before putting the jobs to the list in a loop that verifies whether the job list is full.
  • The control moves to the loop above if the list is empty, where it adds a value to the list.
  • We use an infinite loop in the Consumer class to pull a value from the list.
  • An inner loop that determines whether the list is empty is also present.
  • If empty, we force the consumer thread to release the PC lock and transfer control to the producer thread, creating additional tasks.
  • If the list contains any items, we loop back around and remove one at a time.
  • We utilize notification after every statement in both approaches. The explanation is straightforward: if something is on the list, it can be eaten by a consumer thread or produced by a producer thread, even if you've consumed something.
  • By adding a sleep() after both procedures, you can see what is happening in the program by having the output run step-by-step rather than all at once.

Related Topics

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.

Java LDAP Authentication

WHAT IS LDAP? Clients can communicate with directory services by sending requests and receiving responses using the Lightweight Directory Access Protocol (LDAP). The term "LDAP server" refers to a directory service...

7 minutes read.

Accessors and Mutator in Java

Introduction Accessors and mutators are used in Java to get and set the value of private fields, respectively. Accessors and mutators are both referred to as getters and setters, respectively. The...

6 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

Scanner in Java

Static way of Programming: When a variable can’t change its value during run time is called a Static way of programming. In this programming a variable is directly assigned to a...

4 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.