Write end dead exception using PipedInputStream java

“Write end dead” exceptions will arise when you have:

  • A PipedInputStream connected to a PipedOutputStream and
  • The ends of these pipe are read/written by two different threads
  • The threads finish without closing their side of the pipe.

To resolve this exception, simply close your Piped Stream in your Thread’s runnable after you have completed writing and reading bytes to/from the pipe stream.

Here is some sample code:

final PipedOutputStream output = new PipedOutputStream();
final PipedInputStream input = new PipedInputStream(output);

    Thread thread1 = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                output.write("Hello Piped Streams!! Used for Inter Thread Communication".getBytes());                       
                output.close();

            } catch(IOException io) {
                io.printStackTrace();
            }                   
        }
    });

    Thread thread2 = new Thread(new Runnable() {
        @Override
        public void run() {

            try {

                int data;

                while((data = input.read()) != -1) {
                    System.out.println(data + " ===> " + (char)data);
                }

                input.close();

            } catch(IOException io) {
                io.printStackTrace();
            } 

        }
    });

    thread1.start();
    thread2.start();

Complete code is here: https://github.com/prabhash1785/Java/blob/master/JavaCodeSnippets/src/com/prabhash/java/io/PipedStreams.java

For more details, please have a look at this nice blog: https://techtavern.wordpress.com/2008/07/16/whats-this-ioexception-write-end-dead/

Leave a Comment