Threads and file writing

can it be a problem of synchronization of threads?

Yes.

There’s a way to handle this?

Yes, ensure that writes are serialized by synchronizing on a relevant mutex. Or alternately, have only one thread that actually outputs to the file, and have all of the other threads simply queue text to be written to a queue that the one writing thread draws from. (That way the 20 main threads don’t block on I/O.)

Re the mutex: For instance, if they’re all using the same FileWriter instance (or whatever), which I’ll refer to as fw, then they could use it as a mutex:

synchronized (fw) {
    fw.write(...);
}

If they’re each using their own FileWriter or whatever, find something else they all share to be the mutex.

But again, having a thread doing the I/O on behalf of the others is probably also a good way to go.

Leave a Comment