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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist