java: Runtime.exec() 线程和 errorOutput、readLine
我遇到了非常常见的线程挂起情况,尽管我不明白为什么会发生这种情况。 我有 2 个线程: main() 和 errorStreamReaderThread
在主线程中:
- 通过 Runtime.exec() 执行外部进程
- 创建新的 errorStreamReaderThread 来使用错误输出流
- 对外部进程的输入和输出流执行操作(执行命令并读取命令的输出)
- 向外部进程发送退出命令
- 为 errorStreamReaderThread 设置中断标志
- waitFor() 外部进程终止
- 返回外部进程的rc
在errorStreamReaderThread中:
- 当 !interruptedFlag &&(line=br.readLine())!=null 时对错误流执行 Buffered readLine (errorStream 是从 main 的外部进程传递的)
- 执行日志错误流
我希望即使 readLine() 在流上阻塞 - 一旦该流的发起者完成(在本例中为外部进程),该 readLine 应该被中断。
观察到的行为 - 95% 的时间一切正常 - 两个线程都没有挂起:主线程和错误线程都已完成,程序也已完成。 - 大约 5% 挂起 - 主线程已完成(返回 waitFor) - errorStreamReaderThread 在 BufferedReader.readLine 上被阻塞(事实上,此缓冲读取器的错误流不再存在,因为外部进程已完成)
附加的环境因素是此 java 类作为 oracle java 函数执行(它包装在 oracle 中) )
请让我知道我在这里缺少什么以及为什么我的 readLine 挂在不存在的 errorStream 上,
谢谢
I got very common thread hang condition although I don't understand why it happens.
I have 2 threads: main() and errorStreamReaderThread
In the main thread:
- execute external process via Runtime.exec()
- create new errorStreamReaderThread to consume error output stream
- perform manipulations on input and output streams of external process( execute commands and read output of the commands)
- send exit command to external process
- set interrupt flag for errorStreamReaderThread
- waitFor() for external process to terminate
- return rc of the external process
In the errorStreamReaderThread:
- perform Buffered readLine on error stream while !interruptedFlag &&(line=br.readLine())!=null (errorStream is passed from external process from main)
- perform log error stream
I expect that even though readLine() block on stream - as soon as originator of this stream is finished (external process in this case) this readLine should be interrupted.
Observed behavior
- everything works fine 95% of the time - no hangs, both threads: main and error threads are finished and program finished.
- about 5% it hangs
- main thread is finished (waitFor is returned)
- errorStreamReaderThread is blocked on BufferedReader.readLine (in fact the error stream for this buffered reader is no longer exists, since external process is finished)
Additional environment factor is that this java class is executed as oracle java function (it is wrapped in the oracle)
Please let me know what I'm missing here and why I got this readLine hangs on the non existing errorStream
thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否猜测是这种情况,因为您已向外部进程发送了退出命令,或者您是否确实检查了这两种情况?
由于一旦套接字关闭,BufferedReader.readLine() 将不再阻塞而是返回 null,因此我认为套接字尚未关闭...
Do you guess that this is the case because you have sent an exit command to the external process, or have you really checked both cases?
Since BufferedReader.readLine() will no longer block but return null once the socket closes, I don't think the socket has closed...