使用 PipedInputStream java 编写结束死异常
以下情况会发生写端死异常: 两个线程:
A: PipedOutputStream put = new PipedOutputStream();
String msg = "MESSAGE";
output.wirte(msg.getBytes());
output.flush();
B: PipedInputStream get = new PipedOutputStream(A.put);
byte[] get_msg = new byte[1024];
get.read(get_msg);
情况如下:A 和 B 并发运行,A 写入管道,B 读取管道。 B 刚刚从管道中读取数据,并且该管道的缓冲区被清除。然后 A 不会以未知的时间间隔将 msg 写入管道。然而,在某一时刻,B再次读取管道时,出现了java.io.IOException: write end dead
,因为管道的缓冲区仍然是空的。而且我不想让线程 B sleep() 等待 A 写入管道,这也不稳定。如何避免并解决这个问题呢?谢谢
Write end dead exception occurs in the following situation:
Two threads:
A: PipedOutputStream put = new PipedOutputStream();
String msg = "MESSAGE";
output.wirte(msg.getBytes());
output.flush();
B: PipedInputStream get = new PipedOutputStream(A.put);
byte[] get_msg = new byte[1024];
get.read(get_msg);
Here is the situation: A and B run concurrently, and A writes to the pipe and B reads it. B just read from the pipe and buffer of this pipe is cleared. Then A doesn't write msg to the pipe in unknown interval. However, at one moment, B read the pipe again and java.io.IOException: write end dead
occurs, because the buffer of the pipe is still empty. And I don't want to sleep() thread B to wait for A writing the pipe, which is also unstable. How to avoid this problem and solve it? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您有以下情况时,将出现“写入结束死”异常:
要解决此异常,只需在完成向管道流写入字节和从管道流读取字节后,关闭线程可运行中的管道流即可。
这是一些示例代码:
完整的代码在这里:https ://github.com/prabhash1785/Java/blob/master/JavaCodeSnippets/src/com/prabhash/java/io/PipedStreams.java
有关更多详细信息,请查看这个不错的博客:https://techtavern.wordpress.com/2008/07/16/whats- this-ioexception-write-end-dead/
"Write end dead" exceptions will arise when you have:
To resolve this exception, simply close your Piped Stream in your Thread's runnable after you have completed writing and reading bytes to/from the pipe stream.
Here is some sample code:
Complete code is here: https://github.com/prabhash1785/Java/blob/master/JavaCodeSnippets/src/com/prabhash/java/io/PipedStreams.java
For more details, please have a look at this nice blog: https://techtavern.wordpress.com/2008/07/16/whats-this-ioexception-write-end-dead/
您需要在写入线程完成之前(当然是在写入所有数据之后)关闭PipedOutputStream。当没有写入线程且 writer 未正确关闭时,PipedInputStream 在 read() 上抛出此异常
you need to close PipedOutputStream, before writing thread is finished (and ofcourse after all data is written). PipedInputStream throws this exception on read() when there is no writing thread and writer is not properly closed