What happens when I wrap I/O streams twice?

老子叫甜甜 提交于 2019-12-02 06:05:54

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!