3

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.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Tobia
  • 9,165
  • 28
  • 114
  • 219

2 Answers2

4

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);
        ...
    }
}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • "Ing" is an entity from a Dao object, another thread could get an equal object (but not the same object!) and write to the same file. Am I right? – Tobia Jun 11 '14 at 18:11
  • @Tobia If that's so, then what does `getFile()` do? If it returns the same File object, perhaps you can use that. – RealSkeptic Nov 03 '14 at 08:06
  • Yes, of course getFile() get a File object based on path String. Another time, there can be two different File object pointed to the same path... – Tobia Nov 03 '14 at 10:57
1

By default FileWrite.append() is synchronized.

View in Writer.java.

enter image description here

Albert Khang
  • 621
  • 6
  • 17