将 BufferedWriter.write 推迟到另一个线程
我有一个事件处理方案,它最终也应该写入文件; 当文件被刷新时,我无法延迟事件,即等待 BufferedWriter.write(String) 的末尾。
我正在寻找实现这一目标的最简单方法(是否有一个库可以做到这一点?我认为我不是唯一遇到此问题的人)
I have an event processing scheme which should also eventually write to file; I cannot afford to delay the event when the file is being flushed, i.e. waiting to the end of BufferedWriter.write(String).
I'm looking for the easiest way to achieve that (is there's a library doing that? I reckon that I'm not the only one who had this problem)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用单线程执行器来执行每个事件的文件写入。
只会有一个线程,执行器将负责排队。
You could use an single threaded executor to perform the file writing for each event.
There would only be one thread and the executor would take care of queueing.
基本上,您希望写入文件不会中断事件处理流程。
在这种情况下,您所需要做的就是将文件处理委托给单独的线程。
您的代码应该如下所示:
Basically, you want the writing to the file not interrupt your flow of event handling.
In this case, all you need to do is delegate the file handling away to a separate thread.
Your code should look something like this:
只要保持相同的线程,就可以使用 java.io.PipedOutputStream 来存储数据,并从匹配的 PipedInputStream 到文件中使用单独的线程副本。
So long as you are keeping the same thread, you can use
java.io.PipedOutputStream
to store the data and have separate thread copy from the matchingPipedInputStream
to file.您可以创建一个基于队列的系统,将事件放在队列/列表中,然后使用另一个线程来写入事件并将其写出。 这样,文件编写器将与系统的其余部分异步,唯一的延迟是将元素添加到列表中。
You could make a queue based system, where you put the events on a queue/list and then have another thread which takes the events to be written, and write them out. This way the file writer will be asynchronous to the rest of the system, and your only delay will be adding an element to a list.