PipedReader

The PipedReader class in Java belongs to the java.io package and is used for inter-thread communication. It allows one thread to read character data that another thread has written using a PipedWriter.

Commonly Used Constructors and Methods

Simple Program using PipedReader and PipedWriter

LotusJavaPrince has a system where one thread processes transactions and another logs them to audit. Mahesh writes the transaction strings using PipedWriter, while the logger thread reads them via PipedReader for real-time logging.

import java.io.*;

class TransactionLogger implements Runnable {
    private PipedReader reader;

    public TransactionLogger(PipedReader reader) {
        this.reader = reader;
    }

    public void run() {
        try {
            BufferedReader br = new BufferedReader(reader);
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("Audit Log: " + line);
            }
        } catch (IOException e) {
            System.out.println("Error in logger: " + e.getMessage());
        }
    }
}

class TransactionProcessor implements Runnable {
    private PipedWriter writer;

    public TransactionProcessor(PipedWriter writer) {
        this.writer = writer;
    }

    public void run() {
        try {
            PrintWriter pw = new PrintWriter(writer);
            pw.println("TXN001: $1000 approved");
            pw.println("TXN002: $500 declined");
            pw.println("TXN003: $750 approved");
            pw.close();
        } catch (Exception e) {
            System.out.println("Error in processor: " + e.getMessage());
        }
    }
}

public class CaseStudyPipedReader {
    public static void main(String[] args) throws IOException {
        PipedWriter writer = new PipedWriter();
        PipedReader reader = new PipedReader(writer);

        Thread processor = new Thread(new TransactionProcessor(writer));
        Thread logger = new Thread(new TransactionLogger(reader));

        logger.start();
        processor.start();
    }
}

Output

Audit Log: TXN001: $1000 approved
Audit Log: TXN002: $500 declined
Audit Log: TXN003: $750 approved

PipedReader is useful for inter-thread communication using characters.

  • It must be connected to a PipedWriter.
  • Ideal for decoupling producers and consumers in multi-threaded apps.
  • Always handle synchronization and close streams properly to avoid IOException.
Scroll to Top