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:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular