Program to Create a Thread-Safe Queue in Java

Java




// Java program to create a Thread-Safe Queue
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
  
// Driver Class
public class ThreadSafeQueueExample 
{
      // Main Method
    public static void main(String args[]) 
    {
        // Create a ConcurrentLinkedQueue instance
        Queue<String> threadSafeQueue = new ConcurrentLinkedQueue<>();
  
        // Adding elements to the queue
        threadSafeQueue.add("Element 1");
        threadSafeQueue.add("Element 2");
        threadSafeQueue.add("Element 3");
  
        // Removing elements from the queue
        String element = threadSafeQueue.poll();
        System.out.println("Removed element: " + element);
  
        // Accessing the queue safely from multiple threads
        Runnable producer = () -> {
            for (int i = 0; i < 5; i++) {
                threadSafeQueue.add("New Element " + i);
                System.out.println("Added New Element " + i);
            }
        };
  
        Runnable consumer = () -> {
            while (!threadSafeQueue.isEmpty()) {
                String item = threadSafeQueue.poll();
                System.out.println("Consumed: " + item);
            }
        };
  
        // Create multiple threads to access the queue concurrently
        Thread producerThread = new Thread(producer);
        Thread consumerThread = new Thread(consumer);
  
        producerThread.start();
        consumerThread.start();
  
        try {
            producerThread.join();
            consumerThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
  
        // Printing the remaining elements in the queue
        System.out.println("Remaining elements in the queue: " + threadSafeQueue);
    }
}


Output

Removed element: Element 1
Consumed: Element 2
Consumed: Element 3
Added New Element 0
Added New Element 1
Added New Element 2
Added New Element 3
Added New Element 4
Remaining elements in the queue: ...

Explanation of the above Program:

  • We have used a ConcurrentLinkedQueue to create a thread-safe queue.
  • Then we have added elements and removed from the queue safely.
  • Now, we have created two threads.
  • First one acts as a producer to add elements to the queue, and the second one acts as a consumer to consume elements from the queue.
  • After the threads complete their operations, it prints the queue.


How to Create a Thread-Safe Queue in Java?

In Java, thread-safe is defined as the Queue data structure and it allows multiple threads to safely add and remove elements from the queue concurrently without any data corruption. In a multithreaded environment, the threads access and modify the shared data concurrently, and it is important to ensure that operations on the queue are synchronized to avoid race conditions.

In this article, we will learn how to create a Thread-Safe Queue in Java.

Step-by-Step Implementation

  • Create the class named the ThreadSafeQueueExample and write the main method into it.
  • Create the instance of the ConcurrentLinkedQueue using Queue and it is named as the threadSafeQueue.
  • First, we can add the elements into the threadSafeQueue then poll the element and print it.
  • Now, we can define the producer and consumer runnable and implement the logic of both producer and consumer.
  • Create the thread instance of the producer and consumer then start both threads.
  • Print the remaining elements in the queue.

Similar Reads

Program to Create a Thread-Safe Queue in Java

Java // Java program to create a Thread-Safe Queue import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue;    // Driver Class public class ThreadSafeQueueExample  {       // Main Method     public static void main(String args[])      {         // Create a ConcurrentLinkedQueue instance         Queue threadSafeQueue = new ConcurrentLinkedQueue<>();            // Adding elements to the queue         threadSafeQueue.add("Element 1");         threadSafeQueue.add("Element 2");         threadSafeQueue.add("Element 3");            // Removing elements from the queue         String element = threadSafeQueue.poll();         System.out.println("Removed element: " + element);            // Accessing the queue safely from multiple threads         Runnable producer = () -> {             for (int i = 0; i < 5; i++) {                 threadSafeQueue.add("New Element " + i);                 System.out.println("Added New Element " + i);             }         };            Runnable consumer = () -> {             while (!threadSafeQueue.isEmpty()) {                 String item = threadSafeQueue.poll();                 System.out.println("Consumed: " + item);             }         };            // Create multiple threads to access the queue concurrently         Thread producerThread = new Thread(producer);         Thread consumerThread = new Thread(consumer);            producerThread.start();         consumerThread.start();            try {             producerThread.join();             consumerThread.join();         } catch (InterruptedException e) {             e.printStackTrace();         }            // Printing the remaining elements in the queue         System.out.println("Remaining elements in the queue: " + threadSafeQueue);     } }...