PipedWriter
is a character stream class in the java.io
package used to write characters to a pipe. This pipe can be connected to a PipedReader
which reads the characters written by PipedWriter
. This mechanism facilitates inter-thread communication where one thread writes data, and another reads it.
Commonly Used Constructors and Methods

Simple Program Using PipedWriter
Mahesh and LotusJavaPrince want to simulate a simple chat system using threads. Mahesh acts as a sender writing messages to a PipedWriter
. LotusJavaPrince acts as a receiver reading the messages via a connected PipedReader
. The communication should be thread-safe and continuous until Mahesh sends a termination message "exit"
.
import java.io.*; class ChatSender implements Runnable { private PipedWriter writer; public ChatSender(PipedWriter writer) { this.writer = writer; } @Override public void run() { String[] messages = { "Hello LotusJavaPrince!", "How are you today?", "Did you check the latest update?", "Let's meet tomorrow.", "exit" // Signal to end chat }; try (PrintWriter pw = new PrintWriter(writer)) { for (String msg : messages) { pw.println(msg); pw.flush(); Thread.sleep(500); // Simulate delay between messages } } catch (IOException | InterruptedException e) { System.out.println("Sender error: " + e.getMessage()); } } } class ChatReceiver implements Runnable { private PipedReader reader; public ChatReceiver(PipedReader reader) { this.reader = reader; } @Override public void run() { try (BufferedReader br = new BufferedReader(reader)) { String msg; while ((msg = br.readLine()) != null) { if ("exit".equalsIgnoreCase(msg.trim())) { System.out.println("Chat ended by sender."); break; } System.out.println("LotusJavaPrince received: " + msg); } } catch (IOException e) { System.out.println("Receiver error: " + e.getMessage()); } } } public class ChatApplicationCaseStudy { public static void main(String[] args) throws IOException { PipedWriter writer = new PipedWriter(); PipedReader reader = new PipedReader(writer); Thread senderThread = new Thread(new ChatSender(writer)); Thread receiverThread = new Thread(new ChatReceiver(reader)); receiverThread.start(); senderThread.start(); } }
Output
LotusJavaPrince received: Hello LotusJavaPrince!
LotusJavaPrince received: How are you today?
LotusJavaPrince received: Did you check the latest update?
LotusJavaPrince received: Let's meet tomorrow.
Chat ended by sender.
PipedWriter
provides a way for one thread to send character data to another thread through a connected PipedReader
.It supports thread communication via character streams and must be connected to a PipedReader
.Always ensure proper closing of the streams to avoid resource leaks.