java屏蔽signpipe,PipedInputStream - 如何避免“java.io.IOException:Pipe broken”

I have two threads. One of them writes to PipedOutputStream, another one reads from corresponding PipedInputStream. Background is that one thread is downloading some data from remote server and multiplexes it to several other threads through piped streams.

The problem is that sometimes (especially when downloading large (>50Mb) files) I get java.io.IOException: Pipe broken when trying to read from PipedInputStream.

Javadoc says that A pipe is said to be broken if a thread that was providing data bytes to the connected piped output stream is no longer alive.

It is true, my writing thread really dies after writing all his data to PipedOutputStream.

Any solutions? How can I prevent PipedInputStream from throwing this exception? I want to be able to read all data that was written to PipedOutputStream even if writing thread finished his work. (If anybody knows how to keep writing thread alive until all data will be read, this solution is also acceptable).

解决方案

Use a java.util.concurrent.CountDownLatch, and do not end the first thread before the second one has signaled that is has finished reading from the pipe.

Update: quick and dirty code to illustrate my comment below

final PipedInputStream pin = getInputStream();

final PipedOutputStream pout = getOutputStream();

final CountDownLatch latch = new CountDownLatch(1);

InputStream in = new InputStream() {

@Override

public int read() throws IOException {

return pin.read();

}

@Override

public void close() throws IOException {

super.close();

latch.countDown();

}

};

OutputStream out = new OutputStream(){

@Override

public void write(int b) throws IOException {

pout.write(b);

}

@Override

public void close() throws IOException {

while(latch.getCount()!=0) {

try {

latch.await();

} catch (InterruptedException e) {

//too bad

}

}

super.close();

}

};

//give the streams to your threads, they don't know a latch ever existed

threadOne.feed(in);

threadTwo.feed(out);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值