How to Create a Thread-Safe Queue in Java? Last Updated : 04 Mar, 2024 Suggest changes Share Like Article Like Report 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 ImplementationCreate 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.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); } } OutputRemoved 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. K kadambalamatclo Follow Article Tags : Java Java Programs java-queue Java Examples Explore Java BasicsIntroduction to Java3 min readJava Programming Basics9 min readJava Methods6 min readAccess Modifiers in Java4 min readArrays in Java7 min readJava Strings8 min readRegular Expressions in Java3 min readOOP & InterfacesClasses and Objects in Java9 min readAccess Modifiers in Java4 min readJava Constructors10 min readJava OOP(Object Oriented Programming) Concepts10 min readJava Packages7 min readJava Interface7 min readCollectionsCollections in Java12 min readCollections Class in Java13 min readCollection Interface in Java4 min readIterator in Java5 min readJava Comparator Interface6 min readException HandlingJava Exception Handling6 min readJava Try Catch Block4 min readJava final, finally and finalize4 min readChained Exceptions in Java3 min readNull Pointer Exception in Java5 min readException Handling with Method Overriding in Java4 min readJava AdvancedJava Multithreading Tutorial3 min readSynchronization in Java10 min readFile Handling in Java4 min readJava Method References9 min readJava 8 Stream Tutorial7 min readJava Networking6 min readJDBC Tutorial5 min readJava Memory Management4 min readGarbage Collection in Java6 min readMemory Leaks in Java3 min readPractice JavaJava Interview Questions and Answers15+ min readJava Programs - Java Programming Examples7 min readJava Exercises - Basic to Advanced Java Practice Programs with Solutions5 min readJava Quiz1 min readJava Project Ideas For Beginners and Advanced15+ min read My Profile ${profileImgHtml} My Profile Edit Profile My Courses Join Community Transactions Logout Like