Java NIO Pipe

Pipe is another channel used for communicate between threads.
It has 2 ends, source for read only, and sink for write only.

Create

Simply use open

1
Pipe pipe = Pipe.open();

Write

1
2
3
4
5
6
7
8
9
10
11
12
13
// get the sink/write end of pipe
Pipe.SinkChannel sink = pipe.sink();
String newData = "Rugal Bernstein:" + System.currentTimeMillis();

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();

while (buf.hasRemaining()) {
// same as other channel, just write to it
sink.write(buf);
}

Read

1
2
3
4
5
6
// get source/read end of pipe
Pipe.SourceChannel source = pipe.source();
buf.clear();
// same as other channel, simply read it into byte buffer
source.read(buf);
System.out.println(new String(buf.array()));

Java NIO Pipe
https://rug.al/2020/2020-03-08-java-nio-pipe/
Author
Rugal Bernstein
Posted on
March 8, 2020
Licensed under