HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Multi-threading / Java Inter-thread Communication – PipedReader and PipedWriter

Java Inter-thread Communication – PipedReader and PipedWriter

Java inter-thread communication has been a popular interview question for a long time. With the JDK 1.5 release, ExecutorService and BlockingQueue brought another way of doing it more effectively, but piped stream approach is also worth knowing and might be useful in certain scenarios.

Table of contents

What are piped streams
PipedReader and PipedWriter
Java inter-thread communication example
Summary

What are piped streams

Pipe streams are just like real plumbing pipes. You put things into to a pipe at one end – using some methods. Then you receive the same things back from the pipe stream at the other end – using some other methods.

They come out in FIFO order, first-in first-out, just like from real plumbing pipes.

PipedReader and PipedWriter

PipedReader is an extension of Reader class which is used for reading character streams. Its read() method reads the connected PipedWriter’s stream. Similarly, PipedWriter is an extension of Writer class and does all the things which Reader class contracts.

A writer can be connected to a reader by following two methods:

  1. Using constructor PipedWriter(PipedReader pr)
  2. Using connect(PipedReader pr) method

Once connected through any of above ways, any thread can write data in stream using write(....) methods, and data will be available to reader and can be read using read() method.

Java inter-thread communication example

Below given Java program creates two threads. One thread is responsible for writing into stream and second one is only reading the data to print them in console.

public class PipeReaderThread implements Runnable 
{
    PipedReader pr;
    String name = null;

	public PipeReaderThread(String name, PipedReader pr) 
	{
	    this.name = name;
	    this.pr = pr;
	}

	public void run() 
	{
	    try {
	        // continuously read data from stream and print it in console
	        while (true) {
	            char c = (char) pr.read(); // read a char
	            if (c != -1) { // check for -1 indicating end of file
	                System.out.print(c);
	            }
	        }
	    } catch (Exception e) {
	        System.out.println(" PipeThread Exception: " + e);
	    }
	}
}
public class PipeWriterThread implements Runnable 
{
    PipedWriter pw;
    String name = null;

	public PipeWriterThread(String name, PipedWriter pw) {
	    this.name = name;
	    this.pw = pw;
	}

	public void run() {
	    try {
	        while (true) {
	            // Write some data after every two seconds
	            pw.write("Testing data written...n");
	            pw.flush();
	            Thread.sleep(2000);
	        }
	    } catch (Exception e) {
	        System.out.println(" PipeThread Exception: " + e);
	    }
	}
}
package multiThread;

import java.io.*;

public class PipedCommunicationTest 
{
	public static void main(String[] args) 
	{
	    new PipedCommunicationTest();
	}

	public PipedCommunicationTest() 
	{
	    try 
	    {
	        // Create writer and reader instances
	        PipedReader pr = new PipedReader();
	        PipedWriter pw = new PipedWriter();

	        // Connect the writer with reader
	        pw.connect(pr);

	        // Create one writer thread and one reader thread
	        Thread thread1 = new Thread(new PipeReaderThread("ReaderThread", pr));

	        Thread thread2 = new Thread(new PipeWriterThread("WriterThread", pw));

	        // start both threads
	        thread1.start();
	        thread2.start();

	    } 
	    catch (Exception e) 
	    {
	        System.out.println("PipeThread Exception: " + e);
	    }
	}
}

Program Output:

Testing data written...
Testing data written...
Testing data written...

Summary

  • You cannot write to a pipe without having some sort of reader created and connected to it. In other words, both ends must be present and already connected for the writing end to work.
  • You cannot switch to another reader, to which the pipe was not originally connected, once you are done writing to a pipe.
  • You cannot read back from the pipe if you close the reader. You can close the writing end successfully, however, and still read from the pipe.
  • You cannot read back from the pipe if the thread which wrote to it ends.

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Tarun

    April 15, 2015

    Hi Lokesh,

    Can you also give some live example/applications of InterThread communication using piped

  2. Manjunath.S

    July 27, 2014

    Hello lokesh,
    i have one scenario in java i am struggling to do that could you please help me.
    scenario is
    1.creating two process make communicate with each other using named pipes.
    2. if i send the text in process1 it must display it in other process,that is process2 and vice verse.

    thanks in advance

    • ankit

      November 2, 2019

      same

  3. Surjeet

    December 16, 2013

    Hi lokesh, at one point i read, all primitives types support atomic operation except long and double, if we declare a field of type int, is it necessary to declare that variable as volatile

Comments are closed on this article!

Search Tutorials

Java Concurrency Tutorial

  • Java Concurrency – Introduction
  • Concurrency Evolution
  • Thread Safety
  • Concurrency vs. Parallelism
  • Compare and Swap [CAS]
  • synchronized keyword
  • Object vs. Class Level Locking
  • Runnable vs. Thread
  • wait(), notify() and notifyAll()
  • Yield() vs. Join()
  • Sleep() vs. Wait()
  • Lock vs. Monitor
  • Callable + Future
  • UncaughtExceptionHandler
  • Throttling Task Submission
  • Executor Best Practices
  • Inter-thread Communication
  • Write and Resolve Deadlock

Java Concurrency Utilities

  • AtomicInteger
  • Lock
  • ThreadFactory
  • ThreadLocal
  • ExecutorService
  • ThreadPoolExecutor
  • FixedSizeThreadPoolExecutor
  • ScheduledThreadPoolExecutor
  • Semaphore
  • Binary Semaphore
  • BlockingQueue
  • DelayQueue
  • ConcurrentLinkedDeque
  • CountDownLatch
  • ForkJoinPool

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)