Well, without any implementation detail, it is hard to know, but as my test case shows, I always get 220 lines of output, i.e., constant number of lines, with FileWriter. Notice that no synchronized is used here.
import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * Working example of synchonous, competitive writing to the same file. * @author WesternGun * */ public class ThreadCompete implements Runnable { private FileWriter writer; private int status; private int counter; private boolean stop; private String name; public ThreadCompete(String name) { this.name = name; status = 0; stop = false; // just open the file without appending, to clear content try { writer = new FileWriter(new File("test.txt"), true); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { for (int i=0; i<20; i++) { new Thread(new ThreadCompete("Thread" + i)).start(); } } private int generateRandom(int range) { return (int) (Math.random() * range); } @Override public void run() { while (!stop) { try { writer = new FileWriter(new File("test.txt"), true); if (status == 0) { writer.write(this.name + ": Begin: " + counter); writer.write(System.lineSeparator()); status ++; } else if (status == 1) { writer.write(this.name + ": Now we have " + counter + " books!"); writer.write(System.lineSeparator()); counter++; if (counter > 8) { status = 2; } } else if (status == 2) { writer.write(this.name + ": End. " + counter); writer.write(System.lineSeparator()); stop = true; } writer.flush(); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
As I understand (and test), there are two phases in this process:
- all threads in the pool all created and started, ready to grab the file;
- one of them grabs it, and I guess it then internally locks it, prevents other threads to get access, because I never see a line combined of contents that come from two threads. So when a thread is writing, others are waiting until it completes the line, and very likely, releases the file. So, no race condition will happen.
- the quickest of the others grabs the file and begins writing.
Well, it is just like a crowd waiting outside a bathroom, without queuing.....
So, if your implementation is different, show the code and we can help to break it down.