I have many threads that writes to a pool of files, I want to synchronize filewriter to avoid a dirty append.
Firstly I thought about this:
public synchronized void write(Ing ing) {
File file=getFile(ing);
FileWriter writer;
writer=new FileWriter(file,true);
// ...
}
but this synchronizes all writes, and I want to synchronize only writes on THE SAME file.
To synchronize on each file, it seems that you can synchronize on the ing variable, which contains a reference to the file:
public void write(Ing ing) {
synchronized(ing) {
File file = getFile(ing);
FileWriter writer = new FileWriter(file, true);
...
}
}
By default FileWrite.append() is synchronized.
View in Writer.java.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With