Open In App

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

Program to Create a Thread-Safe Queue in 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:


Article Tags :