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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.