Batch Drain A BlockingQueue With drainTo

Move up to maxElements items out of a BlockingQueue in one locked step with drainTo, so consumer batches stay efficient and never race producers.

JavaResilience

Code

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

public class LogBatchWriter {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(32);
        for (int i = 1; i <= 10; i++) {
            queue.put("event-" + i);
        }

        // drainTo 在一把锁里最多搬走 maxElements 条,比循环 poll 更高效
        List<String> batch = new ArrayList<>();
        int first = queue.drainTo(batch, 6);
        System.out.println("first batch: " + first + " -> " + batch);

        // 不带上限时,drainTo 会搬走当前全部元素
        int rest = queue.drainTo(batch);
        System.out.println("second drain took: " + rest);
        System.out.println("queue empty: " + queue.isEmpty()
                + ", batch size: " + batch.size());
    }
}

How it works

The code’s whole job belongs to the class LogBatchWriter.

One loop does the cycling here: for (int i = 1; i <= 10; i++).

Caveats

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

Using it

Output lines are prefixed (first batch:, second drain took:, queue empty:), which keeps every output line linked to the step that emitted it.

Key statements

BlockingQueue<String> queue = new ArrayBlockingQueue<>(32);
List<String> batch = new ArrayList<>();
int first = queue.drainTo(batch, 6);

Interactive Tools for This Topic

FAQ

What does Batch Drain A BlockingQueue With drainTo print when run?
No setup needed: run the file and look for labeled lines like `first batch:`, `second drain took:`, `queue empty:` in the output.