How to Implement Multiple Blocking Queues with a Single Consumer in Java?

Question

How can I manage multiple blocking queues with a single consumer in a Java application?

import java.util.concurrent.*;

public class MultipleBlockingQueues {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> queue1 = new LinkedBlockingQueue<>();
        BlockingQueue<Integer> queue2 = new LinkedBlockingQueue<>();

        // Producer for queue1
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    queue1.put(i);
                    System.out.println("Produced " + i + " in Queue1");
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }).start();

        // Producer for queue2
        new Thread(() -> {
            for (int i = 10; i < 20; i++) {
                try {
                    queue2.put(i);
                    System.out.println("Produced " + i + " in Queue2");
                    Thread.sleep(150);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }).start();

        // Consumer
        new Thread(() -> {
            try {
                while (true) {
                    Integer item = null;
                    // Poll items from queues
                    if (!queue1.isEmpty()) {
                        item = queue1.take();
                    } else if (!queue2.isEmpty()) {
                        item = queue2.take();
                    }
                    if (item != null) {
                        System.out.println("Consumed " + item);
                    }
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }
}

Answer

Managing multiple blocking queues with a single consumer can enhance performance and lead to efficient resource utilization in a multi-threaded Java application. The process involves using blocking queues to store producer-generated data while ensuring that a single consumer effectively processes items from the queues in a coordinated manner.

BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
try {
    Integer element = queue.take();  // Waits for an element to become available.
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}

Causes

  • Thread safety concerns when modifying shared data structures.
  • Inefficient task scheduling due to improper queue management.
  • Potential blocking if the consumer cannot keep up with the producers.

Solutions

  • Use a priority mechanism to choose which queue to consume from first.
  • Implement timeouts for the consumer when trying to pull from empty queues.
  • Utilize multiple consumers if the workload from the queues becomes too high.

Common Mistakes

Mistake: Assuming all queues will have items at all times, leading to resource contention.

Solution: Implement periodic checks or timeouts when attempting to poll items from the queues to prevent blocking.

Mistake: Not handling InterruptedException properly, which could lead to thread leaks.

Solution: Always handle Interruptions by checking the interrupt flag and breaking out of the loop gracefully.

Helpers

  • Java blocking queue
  • multiple queues single consumer
  • Java concurrency
  • BlockingQueue example
  • Java executor services

Related Questions

⦿How to Measure Scroll Speed in a ListView Component?

Learn how to measure and control scroll speed in ListView components with expertlevel insights and code examples.

⦿How to Resolve Null Values Returned by the Mapper Function in JavaScript?

Learn how to fix null values returned by the mapper function in JavaScript with expert tips code examples and debugging strategies.

⦿How to Resolve Git Pre-Commit Hook Failures Due to Missing Node Command

Learn how to fix Git precommit hook failures caused by the missing Node command with expert troubleshooting tips and solutions.

⦿Resolving NoSuchElementException When Using Java Util Scanner

Learn how to fix NoSuchElementException in Java.Util.Scanner with expert tips and code examples. Understand the causes and solutions effectively.

⦿How to Use Java Reflection getDeclaredMethod() with Class Types

Learn how to effectively use Java Reflections getDeclaredMethod with class types to access specific methods. Understand its usage potential issues and coding tips.

⦿How to Maintain Insertion Order in Java's Map.of Factory?

Learn how to ensure the order of insertion is preserved when using Javas Map.of factory method with expert tips and code examples.

⦿How to Convert a File Array to an ArrayList in Java?

Learn how to convert a File array into an ArrayListFile in Java with examples and common pitfalls.

⦿How to Rotate a Lossless JPEG Image by 90, 180, or 270 Degrees in Java?

Learn how to perform lossless JPEG rotation in Java supporting 90 180 and 270 degrees with code examples and debugging tips.

⦿What is the Difference Between `Files.delete(Path)` and `File.delete()` in Java?

Learn about the differences between Files.deletePath and File.delete in Java including their functionality and usage.

⦿How to Configure Spring Beans with Properties from a Database Table

Learn how to set up Spring beans using configuration properties sourced from a database table. Stepbystep guide and code examples included.

© Copyright 2025 - CodingTechRoom.com