×

Producer consumer problem in Java using Synchronised block

The producer-consumer problem in Java, commonly known as the bounded-buffer problem, is a well-known multi-process synchronization challenge where we attempt to synchronize many processes.

Two processes are involved in the producer-consumer problem: the producer and the consumer. These processes share a single, fixed-size buffer that serves as a queue. Producing data (items) and inserting them into the buffer are the producers' duties. The consumer does data consumption by removing it from the queue.

The difficulty or complications of the producer-consumer problem:

  • When the buffer is filled, the producer shouldn't output more data. In this situation, the producer should wait until the consumer has finished using the data and some buffer space has been freed. 
  • In this instance, the producer should wait until the consumer receives data and some buffer space has been cleared.
  • Whenever the buffer is full, the consumer could consume data. Instead, the consumer can only do so when the buffer is not full (i.e., cannot remove data from the queue).
  • The producer and consumers shouldn't both have simultaneous access to the memory buffer.

Example

Consider a factory that manufactures products and stores them in its storage; the factory will only produce products when it has room in its storage to do so. If the storage is filled, the factory will wait until the product has been consumed before resuming production. Comparably, if the storage is empty, the consumers cannot consume an item. Instead, the consumer must wait until there is another item in the store to consume.

Producer consumer problem in Java using Synchronised block

Solution for producer-consumer problem

We'll implement two main techniques: acquire () and release ().

If a permit is accessible, the acquire() procedure immediately obtains it from the semaphore and returns. Then it subtracts 1 from the total number of permits available.

Suppose no permit is accessible for the current thread. In that case, it enters an inactive state and remains there until either another thread calls the release() procedure, or the other thread terminates the existing thread. When a thread is terminated, the InterruptedException exception will be thrown.

The release() method eliminates a permit, returns it to the semaphore, and raises the total number of available permits by 1. Each thread attempting to obtain a permit is given permission to do so by the semaphore.

The classes in the problem are:

Producer: To build the items that are creating the thing and add them to the buffer.

Consumers: Create objects to take stuff out of the buffer or consumers.

Queue: The queue we wish to synchronise is this one.

Producer, Consumer, and Queue are all created in this class called ThreadSynchronise.

Filename:Synchronisation.java

//Java Program for Producer consumer using Synchronisation
import java.util.concurrent.Semaphore;
class Queue {
    int items;
    static Semaphore Cons = new Semaphore(0);
    static Semaphore Prods = new Semaphore(1);
    // in item is from the buffer
    void gets()
        {
            try {
            
                Cons.acquire();
            }
            catch (InterruptedException e) {
            System.out.println("An InterruptedException caught");
            }
            // the item is consumed by the consumer
            System.out.println("The Consumer consumed item is: " + items);


            // After the consumer notifies to producer
            Prods.release();
    }
	// to put an item in the buffer
    void put(int items)
        {
            try {
                
                Prods.acquire();
            }
            catch (InterruptedException e) {
		System.out.println("An InterruptedException caught");
            }
            // the producer is producing an item
            this.items = items;
 
            System.out.println("The Producer produced item is: " + items);
 
            // after the relase of producer it is verified by consumer
            Cons.release();
	}
}
 
//A class for Producer
class Producers implements Runnable {
    Queue q1;
    Producers(Queue q1)
	{
            this.q1 = q1;
            new Thread(this, "Producers").start();
	}


    public void run()
        {
            for (int i = 0; i < 5; i++)
                q1.put(i);
	}
}
 
// The Consumers Class
class Consumers implements Runnable {
    Queue q1;
    Consumers(Queue q1)
        {
            this.q1 = q1;
            new Thread(this, "Consumers").start();
	}
 
    public void run()
        {
            for (int i = 0; i < 5; i++)
                // the items are retrieved by the consumer
                q1.gets();
        }
}
 
// Main section of the program
class Synchronisation{
    public static void main(String args[])
        {
            // A buffer que is created for storing the values
            Queue q1 = new Queue();
            // The initial is the consumer thread
            new Consumers(q1);
            //The initial Producer thread
            new Producers(q1);
        }
    }

Output

The Producer produced item is: 0
The Consumer consumed item is: 0
The Producer produced item is: 1
The Consumer consumed item is: 1
The Producer produced item is: 2
The Consumer consumed item is: 2
The Producer produced item is: 3
The Consumer consumed item is: 3
The Producer produced item is: 4
The Consumer consumed item is: 4

Related Topics

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Producer consumer problem in Java using Synchronised block

The producer-consumer problem in Java, commonly known as the bounded-buffer problem, is a well-known multi-process synchronization challenge where we attempt to synchronize many processes. Two processes are involved in the producer-consumer problem:...

3 minutes read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

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.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

What is advance Java?

The definition of advance inside the dictionary refers to a forward motion, development, or progress, and the definition of enhancing is something that improves things. To become experts in that...

3 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.