BlockingQueue Take Plus DrainTo Batching

Block with take() for the first queued item, then coalesce all ready elements via drainTo in one consumer pass instead of spinning or polling.

JavaData Fetching

Code

snippet
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class CoalescingConsumer {

    static final String STOP = "__END__";

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue = new LinkedBlockingQueue<>(32);

        Thread producer = new Thread(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    queue.put("msg-" + i);
                }
                queue.put(STOP);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        producer.start();

        List<String> batch = new ArrayList<>();
        boolean running = true;
        while (running) {
            batch.clear();
            // Block until at least one item arrives, then drain any ready peers
            batch.add(queue.take());
            queue.drainTo(batch, 9);
            running = !batch.contains(STOP);
            batch.remove(STOP);
            if (!batch.isEmpty()) {
                System.out.println("flushed batch size=" + batch.size() + " -> " + batch);
            }
        }
        producer.join();
    }
}

Stepwise trace — BlockingQueue Take Plus DrainTo Batching

BlockingQueue Take Plus DrainTo Batching comes down to the class CoalescingConsumer.

A single loop drives the file — for (int i = 1; i <= 5; i++).

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

Console lines carry explicit tags — flushed batch size= — when the file runs.

Key statements

Thread producer = new Thread(() -> {
    try {
        for (int i = 1; i <= 5; i++) {
            queue.put("msg-" + i);
        }
        queue.put(STOP);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
});

FAQ

What does BlockingQueue Take Plus DrainTo Batching print when run?
Execute the whole file; each printed line is prefixed with a label like `flushed batch size=`.