Communicating Between Threads with Piped Streams

The java.io.PipedInputStream class and java.io.PipedOutputStream class provide a convenient means to move streaming data from one thread to another. Output from one thread becomes input for the other thread, as shown in Figure 8.1

Data moving between threads with piped streams

Figure 8-1. Data moving between threads with piped streams

public class PipedInputStream extends InputStream 
public class PipedOutputStream extends OutputStream

The PipedInputStream class has two constructors:

public PipedInputStream()
public PipedInputStream(PipedOutputStream source) throws IOException

The no-argument constructor creates a piped input stream that is not yet connected to a piped output stream. The second constructor creates a piped input stream that’s connected to the piped output stream source.

The PipedOutputStream class also has two constructors:

public PipedOutputStream(PipedInputStream sink) throws IOException
public PipedOutputStream()

The no-argument constructor creates a piped output stream that is not yet connected to a piped input stream. The second constructor creates a piped output stream that’s connected to the piped input stream sink.

Piped streams are normally created in pairs. The piped output stream becomes the underlying source for the piped input stream. For example:

PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pin = new PipedInputStream(pout);

This simple ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.