LinkedTransferQueue Transfer Rendezvous

Hand items to a consumer with LinkedTransferQueue transfer, which blocks until the item is taken, while tryTransfer fails fast when nobody waits.

JavaResilience

Code

snippet
import java.util.concurrent.LinkedTransferQueue;

public class OrderHandoff {

    public static void main(String[] args) throws InterruptedException {
        LinkedTransferQueue<String> lane = new LinkedTransferQueue<>();

        // 消费者先就位:take() 阻塞等待与生产者会合
        Thread packer = new Thread(() -> {
            try {
                for (int i = 0; i < 3; i++) {
                    System.out.println("picked up: " + lane.take());
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "packer");
        packer.start();

        // transfer 的会合语义:阻塞到消费者真正取走才返回
        lane.transfer("order-1");
        lane.transfer("order-2");
        lane.transfer("order-3");

        // packer 已收满 3 件退出循环,此刻无人等待:
        // tryTransfer 立即失败且不入队,队列保持空
        System.out.println("tryTransfer with no consumer: " + lane.tryTransfer("order-4"));
        System.out.println("waiting consumers: " + lane.hasWaitingConsumer());
        System.out.println("queued items: " + lane.size());
    }
}

What the code does

The moving parts are the class OrderHandoff.

Repetition is confined to for (int i = 0; i < 3; i++) — the rest of the file is straight-line.

Applying it

Running the file prints labeled results such as picked up:, tryTransfer with no consumer:, waiting consumers: — each operation’s effect is visible in the output.

Statements that matter

Thread.currentThread().interrupt();

Interactive Tools for This Topic

FAQ

What does LinkedTransferQueue Transfer Rendezvous print when run?
Run it as a complete program — the output lines carry labels such as `picked up:`, `tryTransfer with no consumer:`, `waiting consumers:`.