views:

239

answers:

4

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)

+2  A: 

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:

// 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
Yuval A
I have a lot of events coming - sometimes more than a quarter million per second. I don't think creating a thread for every event would be efficient.
Dani
Of course it won't be efficient. Use a thread pool.
Yuval A
A: 

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.

takete.dk
+4  A: 

You could use an single threaded executor to perform the file writing for each event.

ExecutorService executor = Executors.newSingleThreadExecutor();

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

There would only be one thread and the executor would take care of queueing.

Mark
+1  A: 

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 matching PipedInputStream to file.

Tom Hawtin - tackline