What happens when I wrap I/O streams twice?

后端 未结 2 452
暖寄归人
暖寄归人 2021-01-24 07:40

I know that java I/O uses decorator pattern. But I feel that I understand its wrong.

Please clarify difference between two code snippets:

snippet 1:

         


        
相关标签:
2条回答
  • 2021-01-24 07:52
    PipedInputStream pipedInputStream = new PipedInputStream();
    PipedOutputStream pipedOutputStream = new PipedOutputStream();
    pipedOutputStream.connect(pipedInputStream);
    //writing 
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(pipedOutputStream);
    //ObjectOutputStream objectOutputStreamWrapper =new ObjectOutputStream(objectOutputStream);
    //ObjectOutputStream objectOutputStreamWrapper1=new ObjectOutputStream(objectOutputStreamWrapper);
    //objectOutputStreamWrapper1.writeObject("this is my string");
    //objectOutputStreamWrapper1.flush();
    objectOutputStream.writeObject("this is my string");
    //reading 
    ObjectInputStream objectInputStream = new ObjectInputStream(pipedInputStream);
    //ObjectInputStream objectInputStreamWrapper = new ObjectInputStream(objectInputStream);
    //ObjectInputStream objectInputStreamWrapper1=new ObjectInputStream(objectInputStreamWrapper);
    //System.out.println("going to read from piped source");
    //System.out.println(objectInputStreamWrapper1.readObject());
    System.out.println(objectInputStream.readObject());
    

    Snippet 1 - OutputStream created with Piped stream, then the input stream directly receive the data from the pipe through buffer without flushing.

    Update + 1 - OutputStream created with outputstream wrapper in turn with another wrapper(commented the wrapper statments) and so on works after flush statment. Flush explicitlty flushes the buffered data to the underlying stream, in our case a piped output stream or the output stream .

    Nested stream can be used like FilterOutputStream can be used on top of ObjectOutputStream also.

    0 讨论(0)
  • 2021-01-24 08:03

    You're misusing piped streams. They are intended to be used by a producer thread doing writes and a consumer thread doing reads. See the Javadoc.

    The piped streams share a buffer which can fill if the reading thread isn't reading, which stalls your writing thread.

    Wrapping streams twice doesn't have anything to do with it, although in this case it is certainly both pointless and problematic.

    0 讨论(0)
提交回复
热议问题