Snooze BufferedWriter.write to another thread

I have an event handling scheme that should also be written to a file; I can not afford to delay the event when the file is reset, i.e. Waits for the end of BufferedWriter.write (String).

I am looking for the easiest way to achieve this (is there a library that does this? I believe that I am not the only one who had this problem)

+3
source share
4 answers

You can use a single-threaded executor to write a file for each event.

ExecutorService executor = Executors.newSingleThreadExecutor();

// for each event
executor.submit(new Runnable() {
  public void run()
  {
     // write to the file here
  }
});

There will be only one thread, and the performer will take care of the queue.

+5
source

, , .

, , .

:

// event handling starts

Runnable fileHandlingThread = new Runnable() {
    public void run() {
        // open the file
        // write to the file
        // flush the file
    }
};

new Thread(fileHandlingThread).start();

// continue doing other things in the mean time
+2

, java.io.PipedOutputStream PipedInputStream .

+1

, /, , . , , .

0

Source: https://habr.com/ru/post/1707744/


All Articles