简体   繁体   English

检查 OutputStream 的管道是否损坏

[英]Checking an OutputStream for broken pipe

void sendMessage(String message, OutputStream os) {
    try {
        ExternalLibrary.sendMessage(message, os);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I have the above bit of code that uses an external method to send a message through an output stream.我有上面的代码,它使用外部方法通过输出流发送消息。 If there's an IO exception (eg a broken pipe), that method will perform some logging and throw than IOException.如果有 IO 异常(例如管道损坏),该方法将执行一些日志记录并抛出 IOException。 I want to prevent the logging from happening if there's a broken pipe.如果管道损坏,我想防止日志记录发生。 The logging performed by the method is vague and difficult to look through, so I only want to call it if I can be reasonably sure the pipe isn't broken.该方法执行的日志记录含糊不清且难以查看,因此我只想在可以合理确定管道没有损坏的情况下调用它。 Something like:就像是:

void sendMessage(String message, OutputStream os) {
    if (!os.isClosed()) {
        try {
            ExternalLibrary.sendMessage(message, os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        logger.error("Broken pipe");
    }
}

Since you are in a MultiThreaded environment you can never be sure if a asynchrouius task invalidate the OutputStream throu a different Thread.由于您处于多线程环境中,您永远无法确定异步任务是否通过不同的线程使 OutputStream 无效。

A simplified example:一个简化的例子:

You start the sending of the message.您开始发送消息。 Right after sending the message your PC is running out of RAM, the OutputStream breaks because it can not allocate more RAM - voila your stream is broken.发送消息后,您的 PC 的 RAM 不足,OutputStream 中断,因为它无法分配更多 RAM - 瞧,您的流中断了。 This is happening after the calling of the function but before the leave of the function.这是在调用函数之后但在函数离开之前发生的。

The concept of "broken" is unknown to a OutputStream! “损坏”的概念对于输出流来说是未知的! Also a Pipe is a different kind of design.管道也是一种不同的设计。 You mean Streams.你的意思是流。

Only the method write(*) is able to produce a IOException what can be used to express a broken pipe.只有方法write(*)能够产生一个IOException ,它可以用来表示管道损坏。

Unfortunately the method write(*) is called inside ExternalLibrary.sendMessage(message, os);不幸的是,方法write(*)是在ExternalLibrary.sendMessage(message, os);内部调用的ExternalLibrary.sendMessage(message, os); . .

That is too late for your task to你的任务来不及了

call it if I can be reasonably sure the pipe isn't broken如果我可以合理地确定管道没有损坏,就调用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM