本文介绍了更好的替代PipedReader / PipedWriter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个缓冲的 char 流,我在一个线程中写入,从另一个线程中读取。 我正在使用和 ,但这些类会导致性能问题:PipedReader在其内部缓冲区为空时执行 wait(1000),这会导致我的应用程序明显滞后。

I need to have a buffered char stream, into which I write in one thread and from which I read in another thread. Right now I'm using PipedReader and PipedWriter for it, but those classes cause a performance problem: PipedReader does a wait(1000) when its internal buffer is empty, which causes my application to lag visibly.

有没有一些图书馆做与PipedReader / PipedWriter相同的事情,但性能更好?或者我必须实现自己的轮子?

Would there be some library which does the same thing as PipedReader/PipedWriter, but with better performance? Or will I have to implement my own wheels?

推荐答案

问题是当有东西写到PipedWriter时,它不会自动通知PipedReader有一些数据要读取。当您尝试读取PipedReader并且缓冲区为空时,PipedReader将循环并使用 wait(1000)调用直到缓冲区有一些数据。

The problem was that when something is written to the PipedWriter, it does not automatically notify the PipedReader that there is some data to read. When one tries to read PipedReader and the buffer is empty, the PipedReader will loop and wait using a wait(1000) call until the buffer has some data.

解决方案是在写入管道后总是调用 PipedWriter.flush()。所有刷新功能都在读卡器上调用 notifyAll()。有关代码的修复。

The solution is to call PipedWriter.flush() always after writing something to the pipe. All that the flush does is call notifyAll() on the reader. The fix to the code in question looks like this.

(对我来说,PipedReader / PipedWriter实现看起来非常像一个过早优化的情况 - 为什么不在每次写入时通知所有的内容?读者还在等待一个主动循环,每秒醒来,而不是只有当有东西要醒来时才会醒来,代码还包含一些待评论,读者/作者的线程检测是不够复杂的。)

(To me the PipedReader/PipedWriter implementation looks very much like a case of premature optimization - why not to notifyAll on every write? Also the readers wait in an active loop, waking up every second, instead of waking only when there is something to read. The code also contains some todo comments, that the reader/writer thread detection which it does is not sophisticated enough.)

同样的问题似乎也在),所以我通过创建。他们的工作比原来的班级要好得多。 : - )

This same problem appears to be also in PipedOutputStream. In my current project calling flush() manually is not possible (can't modify Commons IO's IOUtils.copy()), so I fixed it by creating low-latency wrappers for the pipe classes. They work much better than the original classes. :-)

这篇关于更好的替代PipedReader / PipedWriter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 01:56