Java IO: Pipes
Pipes in Java IO provides the ability for two threads running in the same JVM to communicate. Therefore pipes can also be sources or destinations of data.
You cannot use a pipe to communicate with a thread in a different JVM (different process). The pipe concept in Java is different from the pipe concept in Unix / Linux, where two processes running in different address spaces can communicate via a pipe. In Java, the communicating parties must be running in the same process, and should be different threads.
Creating Pipes via Java IO
Creating a pipe using Java IO is done via the PipedOutputStream
and PipedInputStream
classes. A PipedInputStream
should be connected to a PipedOutputStream
. The data written to the PipedOutputStream
by one thread can be read from the connected PipedInputStream
by another thread.
Java IO Pipe Example
Here is a simple example of how to connect a PipedInputStream
to a PipedOutputStream
:
You can also connect the two pipe streams using their connect()
methods. Both PipedInputStream
and PipedOutputStream
has a connect()
method that can connect one to the other.
Pipes and Threads
Remember, when using the two connected pipe streams, pass one stream to one thread, and the other stream to another thread. The read()
and write()
calls on the streams are blocking, meaning if you try to use the same thread to both read and write, this may result in the thread deadlocking itself.
Pipe Alternatives
There are many other ways than pipes that threads can communicate within the same JVM. In fact, threads more often exchange complete objects rather than raw byte data. But - if you need to exchange raw byte data between threads, Java IO's pipes are a possibility.
Last updated