PipedInputStream - How to avoid "java.io.IOException: Pipe broken" PipedInputStream - How to avoid "java.io.IOException: Pipe broken" multithreading multithreading

PipedInputStream - How to avoid "java.io.IOException: Pipe broken"


Use a java.util.concurrent.CountDownLatch, and do not end the first thread before the second one has signaled that is has finished reading from the pipe.

Update: quick and dirty code to illustrate my comment below

    final PipedInputStream pin = getInputStream();    final PipedOutputStream pout = getOutputStream();    final CountDownLatch latch = new CountDownLatch(1);    InputStream in = new InputStream() {        @Override        public int read() throws IOException {            return pin.read();        }        @Override        public void close() throws IOException {            super.close();            latch.countDown();        }    };    OutputStream out = new OutputStream(){        @Override        public void write(int b) throws IOException {            pout.write(b);        }        @Override        public void close() throws IOException {            while(latch.getCount()!=0) {                try {                    latch.await();                } catch (InterruptedException e) {                    //too bad                }            }            super.close();        }    };    //give the streams to your threads, they don't know a latch ever existed    threadOne.feed(in);    threadTwo.feed(out);


Are you closing your PipedOutputStream when the thread that's using it ends? You need to do this so the bytes in it will get flushed to the corresponding PipedInputStream.


PipedInputStream and PipedOutputStream are broken (with regards to threading). They assume each instance is bound to a particular thread. This is bizarre. I suggest using your own (or at least a different) implementation.