Java PipedInputStream & PipedOutputStream


PipedInputStream and PipedOutputStream in Java create a pipe for communication between two threads.

 

A PipedInputStream allows for reading any data that has been written to a PipedOutputStream.

 

notepad

Used for inter-thread communication in producer-consumer scenarios.


Syntax

Create Pipe

PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos); // Connected 

 

Or connect later:

 PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
pos.connect(pis);

Example

import java.io.*;

public class PipeExample {
    public static void main(String[] args) throws IOException {
        final PipedInputStream pis = new PipedInputStream();
        final PipedOutputStream pos = new PipedOutputStream(pis);

        Thread writer = new Thread(() -> {
            try {
                String message = "Hello from writer thread!";
                pos.write(message.getBytes());
                pos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        Thread reader = new Thread(() -> {
            try {
                int data;
                while ((data = pis.read()) != -1) {
                    System.out.print((char) data);
                }
                pis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        writer.start();
        reader.start();
    }
}

Output

Hello from writer thread! 

PipedOutputStream

Method Description
write(int b) Writes a byte to the stream
write(byte[] b) Writes an array of bytes
close() Closes the stream

PipedInputStream

Method Description
read() Reads one byte of data
read(byte[] b) Reads bytes into the array
available() Number of bytes available to read
close() Closes the stream

Key Points

  • Inter-thread communication requires the use of pipes between distinct threads.
  • Users need to connect both ends of the pipe before they can begin operating with it.
  • Always handle exceptions and close streams.
  • This communication method does not support thread-safe operations involving multiple writers or readers.



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.