Java-PipedWriter and PipedReader

PipedWriter and PipedReader

The PipedWriter class and PipedReader class provide functionality for threads to communicate and exchange data between them. The PipedWriter class lets a sending thread write a stream of characters to an instance of the PipedReader class, which a receiving thread uses to subsequently read those characters, as shown in following figure :

pipedreader

PipedWriter declares a void connect(PipedReader snk) method that connects this piped writer to snk. This method throws IOException when this piped writer stream is already connected to another piped reader stream. The easiest way to create a pair of piped streams is in the same thread and in either order. For example, you can first create the piped writer stream:

Alternatively, you can first create the piped reader stream:

You can leave both streams unconnected and later connect them to each other using the appropriate piped stream’s connect() method, as follows :

The piped reader stream also has four fields and receive() methods that are used to implement the piping:

1) private static final int DEFAULT_PIPE_SIZE = 1024
2) char buffer[]
3) int in
4) int out
5) protected synchronized void receive(int c) throws IOException

DEFAULT_PIPE_SIZE is a named constant for the size of the buffer. It’s 1024 in Java 1.1 and 1.2. The buffer is the character array where the data is stored, and it’s initialized to be an array of length DEFAULT_PIPE_SIZE . When a client class invokes a write() method in the piped writer stream class, the write() method invokes the receive() method in the connected piped reader stream to place the data in the character array buffer. Data is always written at the position in the buffer given by the field in and read from the position in the buffer given by the field out.

Possible Blocking Situations

There are two possible blocking situations here. The first occurs if the writing thread tries to write data while the reading thread’s input buffer is full. When this occurs, the writer stream enters an infinite loop in which it repeatedly waits for one second until some thread reads some data out of the buffer and frees up space. If this is likely to be a problem for your application, you should subclass PipedReader and make the buffer larger.

The second possible block is when the reading thread tries to read and no data is present in the buffer. In this case, the reader stream enters an infinite loop in which it repeatedly waits for one second until some thread writes some data into the buffer. Although PipedReader contain an internal buffer, they do not support marking and resetting.

Caution

Attempting to use a PipedWriter object and a PipedReader object from a single thread is not recommended because it might deadlock the thread. The Exception is said to be ‘Pipe broken’ if a thread that was reading characters from the connected piped reader stream is no longer alive.


PipedWriter Constructors

Constructor Description
PipedWriter() Creates a piped writer that is not yet connected to a piped reader.
PipedWriter(PipedReader snk) Creates a piped writer connected to the specified piped reader.



PipedWriter Methods

Method Description
void connect(PipedReader snk) Connects this piped writer to a receiver.
void write(int c) Writes a character(int to char) to the piped output stream.
void write(char[] c) Writes an array of characters to the piped output stream.
void write(char[] c, int off, int len) Writes a portion of an array of characters to the piped output stream.
void write(String str) Write a string to the piped output stream.
void write(String str, int off, int len) Write a portion of a string to the piped output stream.
CharArrayWriter append(char c) Appends the specified character to the piped output stream.
CharArrayWriter append(CharSequence csq) Appends the specified character sequence to the piped output stream.
CharArrayWriter append(CharSequence csq, int start, int end) Appends a subsequence of the specified character sequence to the piped output stream.
void     flush() Flushes this output stream and forces any buffered output characters to be written out.
void     close() Closes this piped output stream and releases any system resources associated with this stream. This stream may no longer be used for writing characters.



PipedReader Constructors

Constructor Description
PipedReader() Creates a PipedReader so that it is not yet connected.
PipedReader(int pipeSize) Creates a PipedReader so that it is not yet connected and uses the specified pipe size for the pipe’s buffer.
PipedReader(PipedWriter src) Creates a PipedReader so that it is connected to the piped writer src.
PipedReader(PipedWriter src, int pipeSize) Creates a PipedReader so that it is connected to the piped writer src and uses the specified pipe size for the pipe’s buffer.



PipedReader Methods

Method Description
void connect(PipedWriter src) Causes this piped reader to be connected to the piped writer src.
int read() Reads a single character from this piped stream.
int read(char[ ] cb) Reads up to cb.length characters from this piped stream into an array of characters.
int read(char[ ] cb, int off, int len) Reads up to len characters from this piped stream into an array of characters.
int read(CharBuffer cb) Attempts to read characters from this piped stream into the specified character buffer.
boolean  ready() Tells whether this stream is ready to be read.
long        skip(long n) Skips over and discards n characters from this piped stream.
void        close() Closes the stream and releases any system resources associated with it.


Program

pipedreader

Program Source

import java.io.PipedWriter;
import java.io.PipedReader;
import java.io.IOException;

public class Javaapp {

    public static void main(String[] args) throws IOException {
        
        PipedWriter writer = new PipedWriter();
        PipedReader reader = new PipedReader();
        reader.connect(writer);
        
        Thread writerThr = new Thread(()-> {
            
            for(int i=65;i<75;i++)
            {
                try{
                    writer.write(i);
                    Thread.sleep(2000);
                    if(i==74)
                    {
                        writer.close();
                    }
                }catch(Exception e)
                {
                    System.out.println(e);
                }
            }
        });
        writerThr.start();
        
        int getc=0;
        while((getc=reader.read())!=-1)
        {
            System.out.println("MainThr reading : "+(char)getc);
        }
        reader.close();
    }
}

Leave a Comment