Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Synchronize filewrite

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.

like image 787
Tobia Avatar asked Feb 24 '26 13:02

Tobia


2 Answers

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);
        ...
    }
}
like image 105
Jean Logeart Avatar answered Feb 26 '26 02:02

Jean Logeart


By default FileWrite.append() is synchronized.

View in Writer.java.

enter image description here

like image 29
Albert Khang Avatar answered Feb 26 '26 03:02

Albert Khang