×

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 Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Duodecimal in Java

Duodecimal is a notation style in which a number with a base of 12 is referred to be a duodecimal number. In Java, we can use to convert duodecimal integers...

2 minutes read.

Java AWT

Java AWT Java programming is used to develop different types of applications like window-based applications, web applications, Enterprise applications, or mobile applications. For creating standalone applications, Java AWT API is used....

11 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.