Search code examples
javanio

Is there any way to pipe two channels?


I have a ReadableByteChannel and a WritableByteChannel, now I want to pipe the output from the readable byte channel to the writable byte channel. In other words — when there are bytes available in the readable channel, I want to write them to the writable channel.

Could I do this without a new thread?


Solution

  • Well ... you can't do it in Java without any user-space thread. It is not possible in standard Java to tell the OS to "replug" two file descriptors and short-circuit the data transfer.

    (I'm not aware of any modern mainstream OS that supports this kind of thing. Though it is not a ridiculous idea. If anyone knows of an example of an OS with this kind opf functionality, please comment ...)

    However, if you use the SelectableChannel and Selector APIs, a thread can intersperse the "piping" with doing other things, including other (selector-based) I/O on other channels.