LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Concurrency and Executors Programs · Question 3

Order processing pipeline with BlockingQueue in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Build a pipeline: a producer puts orders into a LinkedBlockingQueue, two workers from an executor validate them and add valid order totals to a LongAdder, using a poison pill per worker to stop; print the totals.

Solution
Main.java
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

record Order(String id, int amount) { }

public class Main {
    static final Order POISON = new Order("STOP", 0);

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Order> queue = new LinkedBlockingQueue<>(3);
        LongAdder revenue = new LongAdder();
        AtomicInteger rejected = new AtomicInteger();
        int workers = 2;

        try (ExecutorService pool = Executors.newFixedThreadPool(workers)) {
            for (int w = 0; w < workers; w++) {
                pool.submit(() -> {
                    for (Order o; (o = queue.take()) != POISON; ) {
                        if (o.amount() > 0) revenue.add(o.amount()); else rejected.incrementAndGet();
                    }
                    return null;
                });
            }
            int[] amounts = {499, 1299, -5, 250, 0, 3999, 120};
            for (int i = 0; i < amounts.length; i++) queue.put(new Order("O" + i, amounts[i]));
            for (int w = 0; w < workers; w++) queue.put(POISON);     // one stop signal per worker
        }
        System.out.println("revenue " + revenue.sum() + ", rejected " + rejected.get() + ", queue empty " + queue.isEmpty());
    }
}

Output Verified by compiling and running

revenue 6167, rejected 2, queue empty true

The bounded queue applies back-pressure to the producer; LongAdder and AtomicInteger collect results without locks; one poison pill per worker shuts them all down.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links