Pass Data Between Threads Using Piped Streams

Pass Data Between Threads Using Piped Streams

Java simplifies I/O by providing a rich library of classes that support stream interfaces. Among these classes, the combination of PipedInputStream and PipedOutputtStream closely resembles a UNIX system “pipe.” The purpose of these “piped stream” classes is to allow the program to read data into an input stream and write it out through an output stream in a single method call.

Pipes are typically used in threaded programs. Consider a program that spawns two threads. One of the threads writes out data that it reads from a data source. The other reads this data and processes it. One way to achieve this functionality is to open an output stream in the first thread and have it continuously write out the data to some shared storage. You would also have to open an output stream (in the second thread), which would read in the data from the shared storage.

An alternative is to use the “piped stream” classes. In order to achieve the same objective, instantiate a PipedInputStream and a PipeOutputStream. Then connect the two streams so that the writes from the output stream go to the input stream. After that, every time the first thread writes some data using the write() call, a corresponding read() on the input stream will make it available to the second thread.


Share the Post: