PipedInputStream
is used to read data written to a connected PipedOutputStream
. It provides a communication pipe between two threads, enabling one thread to write data and another to read it.This class is part of Java’s inter-thread communication system and works in conjunction with PipedOutputStream
.
Commonly Used Constructors and Methods


Simple Program – Inter-thread Communication
Mahesh writes data using PipedOutputStream
, and LotusJavaPrince reads it using PipedInputStream
. Demonstrate basic inter-thread communication.
import java.io.*; public class SimplePipedExample { public static void main(String[] args) throws IOException { PipedInputStream pipedIn = new PipedInputStream(); PipedOutputStream pipedOut = new PipedOutputStream(pipedIn); Thread writer = new Thread(() -> { try { pipedOut.write("Hello from Mahesh!".getBytes()); pipedOut.close(); } catch (IOException e) { e.printStackTrace(); } }); Thread reader = new Thread(() -> { try { int data; while ((data = pipedIn.read()) != -1) { System.out.print((char) data); } pipedIn.close(); } catch (IOException e) { e.printStackTrace(); } }); writer.start(); reader.start(); } } /* Hello from Mahesh! */
Problem Statement:
LotusJavaPrince is building a live transaction processing system. Mahesh simulates transaction data and writes it using PipedOutputStream
. LotusJavaPrince reads and processes transactions using PipedInputStream
in real-time between two threads.
import java.io.*; class TransactionWriter extends Thread { private final PipedOutputStream out; public TransactionWriter(PipedOutputStream out) { this.out = out; } public void run() { String[] transactions = { "TXN001:Deposit:1000", "TXN002:Withdraw:500", "TXN003:Deposit:700" }; try { for (String txn : transactions) { out.write((txn + "\n").getBytes()); Thread.sleep(500); // simulate delay } out.close(); } catch (Exception e) { e.printStackTrace(); } } } class TransactionReader extends Thread { private final PipedInputStream in; public TransactionReader(PipedInputStream in) { this.in = in; } public void run() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { String line; while ((line = reader.readLine()) != null) { System.out.println("Processing: " + line); } } catch (IOException e) { e.printStackTrace(); } } } public class BankTransactionPipe { public static void main(String[] args) throws IOException { PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(pos); new TransactionWriter(pos).start(); new TransactionReader(pis).start(); } }
Output
Processing: TXN001:Deposit:1000
Processing: TXN002:Withdraw:500
Processing: TXN003:Deposit:700
Code language: CSS (css)
PipedInputStream
enables efficient communication between threads.
- Works together with
PipedOutputStream
. - Ideal for real-time, memory-based communication inside applications.
- Supports blocking reads and helps build stream-like producer-consumer systems.