×

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 Editors

A straightforward text editor may be used to create Java applications. However, a Java integrated programming environment (IDE) enables the software developer to create programs more quickly. An IDE offers...

4 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

How to convert float to String in Java

How to convert float to String in java There are following methods to convert float to String: Convert using Float.toString(float) Convert using String.valueOf(float) Convert using Float.toString(float) The Float class has a static method that returns...

2 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

Reserved Keywords in Java

In Java, a reserved term is used as a code key called a keyword. Because they are predefined, these terms cannot be used for anything else. They cannot serve as...

3 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java...

4 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 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.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.