TeeInputStream and PipedStream does not work in any case

2.3k views Asked by At

I run into a problem while "cloning" an InputStream.

This does not work:

InputStream is = ClassLoader.getSystemResourceAsStream("myResource");

But this works:

InputStream is = new BufferedInputStream(new FileInputStream("/afas.cfg"));

My code is:

// Create a piped input stream for one of the readers.
PipedInputStream in = new PipedInputStream();

// Create a tee-splitter for the other reader.(from apache commons io)
TeeInputStream tee = new TeeInputStream(is, new PipedOutputStream(in));

// Create the two buffered readers.
BufferedReader br1 = new BufferedReader(new InputStreamReader(tee));
BufferedReader br2 = new BufferedReader(new InputStreamReader(in));

// Do some interleaved reads from them.
System.out.println("One line from br1:");
System.out.println(br1.readLine());
System.out.println();

System.out.println("Two lines from br2:");
System.out.println(br2.readLine());
System.out.println(br2.readLine());
System.out.println();

System.out.println("One line from br1:");
System.out.println(br1.readLine());
System.out.println();

The problem occurs at the first br1.readLine() call. It just get stuck at PipedInputStream.awaitSpace() and is in an endless loop.

Are the PipedStreams only for threads? Meaning that when writing to the PipedOutputStreams the PipedInputStream would "wake up"

What do i have to do to get this work in any case?

1

There are 1 answers

0
user207421 On BEST ANSWER

This is a misuse of piped streams. They are intended to be used by different threads. They will not work as you are using them here, because there is a 4k buffer and the writer blocks when it fills. From the Javadoc:

Attempting to use both objects from a single thread is not recommended, as it may deadlock the thread.

Personally I have never encountered a valid use for these piped streams since May 1997. I used one once back then and took it out immediately in favour of a queue.