BlockingQueue Timed offer poll Timeout Path

Timed offer and poll give up after the timeout instead of blocking forever: a full queue returns false, an empty one null, and neither path throws.

JavaResilience

Code

snippet
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class TimedQueueOps {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> inbox = new ArrayBlockingQueue<>(2);

        // offer:队列满时立即返回 false,不阻塞也不抛异常
        System.out.println("offer a: " + inbox.offer("a"));
        System.out.println("offer b: " + inbox.offer("b"));
        System.out.println("offer c (full): " + inbox.offer("c"));

        // 带时限的 offer:最多等 50ms,队列仍满就放弃
        System.out.println("timed offer (full): " + inbox.offer("c", 50, TimeUnit.MILLISECONDS));

        // poll:空队列立即返回 null;带时限的 poll 最多等到期限
        System.out.println("poll: " + inbox.poll());
        System.out.println("poll again: " + inbox.poll());
        System.out.println("timed poll on empty: " + inbox.poll(80, TimeUnit.MILLISECONDS));
    }
}

Inside the snippet

BlockingQueue Timed offer poll Timeout Path keeps everything in the class TimedQueueOps.

Putting it to use

The run emits 7 labeled sections — offer a:, offer b:, offer c (full):, timed offer (full):, poll:, poll again:, timed poll on empty: — one per step.

Core lines

BlockingQueue<String> inbox = new ArrayBlockingQueue<>(2);

Interactive Tools for This Topic

FAQ

What does BlockingQueue Timed offer poll Timeout Path print when run?
Invoke the file as-is — the `offer a:`, `offer b:`, `offer c (full):` prefixes identify which step printed each line.