简体   繁体   English

用一个编写器线程(Java)替换写入输出流的多个线程

[英]replacing multiple threads writing to outputstream with one writer thread (Java)

I have an existing app where multiple threads are writing via an outputstream (and synchronizing on it). 我有一个现有的应用程序,其中多个线程通过一个outputstream编写(并在其上同步)。 I am wondering whether switching over to a single writer principle for writing to the outputstream might be more efficient (I am just doing this for academic reasons as I do not believe this will impact the app performance that much though I could be wrong). 我想知道切换到单一编写器原则以写入输出流是否会更有效(我只是出于学术原因这样做,因为我不相信这会严重影响应用程序性能,尽管我可能错了)。 For now, I am only thinking of using a blockingqueue or a ring buffer for all current writers to write to and one writer thread (consumer for the queue/ringbuffer) to write to the output stream/channel. 就目前而言,我只在考虑使用阻塞队列或环形缓冲区供所有当前写入器写入,并使用一个写入器线程(队列/环形缓冲区使用)写入输出流/通道。
Any thoughts on this or helpful suggestions would be quite welcome. 任何对此的想法或有用的建议都将受到欢迎。

If you have enough free capacity on your system (idle CPU time, available IO time) then adding a separate thread to do the logging IO only will noticeably improve the performance of the overall system. 如果系统上有足够的可用容量(空闲CPU时间,可用IO时间),则添加单独的线程仅执行日志IO将显着提高整个系统的性能。

Adding a Queue from the java.util.concurrent package with a bunch of threads that add to the queue, and a logging thread that reads from the queue and writes out the output will be a good solution. java.util.concurrent包中添加一个队列,并添加一堆添加到队列中的线程,并从该队列中读取并写出输出的日志记录线程将是一个很好的解决方案。

On the other hand, if you have a fully utilized system then the queue will either become too large, or the overhead will become noticable, and the benefits of the logging thread will become negligible. 另一方面,如果您具有充分利用的系统,则队列将变得太大,或者开销将变得明显,并且日志线程的好处将变得微不足道。

In most cases I have seen a seperate logging thread is beneficial. 在大多数情况下,我看到一个单独的日志记录线程是有益的。

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

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