Pipe Channels Between Threads

Move bytes between threads through a NIO Pipe, using a dedicated writer thread and an EOF read loop instead of a shared buffer.

JavaResilience

Code

snippet
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.charset.StandardCharsets;

public class PipeChannelDemo {
    public static void main(String[] args) throws Exception {
        // Pipe:单向字节通道,source 读、sink 写
        Pipe pipe = Pipe.open();
        Pipe.SinkChannel sink = pipe.sink();
        Pipe.SourceChannel source = pipe.source();

        Thread writer = new Thread(() -> {
            try {
                for (String line : new String[]{"alpha", "beta", "gamma"}) {
                    ByteBuffer buf = ByteBuffer.wrap((line + "\n").getBytes(StandardCharsets.UTF_8));
                    while (buf.hasRemaining()) {
                        sink.write(buf);
                    }
                }
                sink.close(); // 关闭写端,读端随后读到 EOF
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "pipe-writer");
        writer.start();

        ByteBuffer buffer = ByteBuffer.allocate(64);
        StringBuilder received = new StringBuilder();
        while (source.read(buffer) != -1) {
            buffer.flip();
            received.append(StandardCharsets.UTF_8.decode(buffer));
            buffer.clear();
        }
        writer.join();
        source.close();

        System.out.println("received: " + received.toString().trim().replace("\n", ","));
    }
}

How the snippet works

Pipe Channels Between Threads keeps everything in the class PipeChannelDemo.

Repetition is confined to for (String line : new String[]{"alpha", "beta", "gamma"}) — the rest of the file is straight-line.

Applying it

The demo output is labeled (received:), so every printed line maps back to its originating operation.

Statements that matter

ByteBuffer buf = ByteBuffer.wrap((line + "\n").getBytes(StandardCharsets.UTF_8));

Interactive Tools for This Topic

FAQ

What does Pipe Channels Between Threads print when run?
Running the file directly is enough — expect labeled output lines such as `received:`.