Reputation: 9506
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.
Upvotes: 3
Views: 4631
Reputation: 701
By default FileWrite.append() is synchronized.
View in Writer.java
.
Upvotes: 1
Reputation: 53809
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);
...
}
}
Upvotes: 4