Hello, such a problem is that the loop that should end when the method of the PipedInputStream object returns -1 , but it does not return. How to be? Where am I wrong? Tell me please.

 public void rw1() { StringBuilder sb = new StringBuilder(); try (PipedOutputStream out = new PipedOutputStream(); PipedInputStream in = new PipedInputStream(out) ) { out.write("message".getBytes("UTF8")); out.flush(); int data = in.read(); while ((data) != -1) { sb.append((char) data); System.out.println(data); data = in.read(); } System.out.println(new String(sb)); } catch (IOException e) { e.printStackTrace(); } } 

The execution flow simply stops and does not go any further.

I understand that he is waiting for more data, I could use the available() method, but I still want to understand the logic with this -1 which read() should return. What is the matter?

    1 answer 1

    PipedInputStream.read method blocking according to the documentation:

    Read this from the piped input stream. This is the number of thirteen.

    Those. The method blocks execution until one of the following events occurs:

    • data available for reading will appear, then the method will return the read byte;
    • the input stream ends (in your case this happens if the out closes), then the method will return -1;
    • an exception will occur.

    Because out does not close, -1 will never return. The stream will wait for the following data.

    I understand that he is waiting for more data, one could use the available() method ...

    In principle, you understand everything correctly and yes, in this case you can use non-blocking reading ( available() ).