×

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

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

How to find the length of an Array in Java

Arrays: An array is a sort of container object that stores constant quantities of values of a single type in one memory area. A finite number of items must all be...

3 minutes read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Java Integer toOctalString() method

The toOctalString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 8. Syntax public static String toOctalString (int  i) Parameters The parameter ‘i’ represents...

1 minute read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

Java Boolean getBoolean() Method

The getBoolean() method of Java Boolean class returns true if the specified system property is not null and is equal to the String ‘true’, else the result returned is false. Syntax public...

1 minute read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

Java String valueOf() method

Java String valueOf() method converts different types of values into String. Such as : int to String, long to String, boolean to String, character to String, float to String, double to...

2 minutes read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.