Tobia
Tobia

Reputation: 9506

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.

Upvotes: 3

Views: 4631

Answers (2)

albertkhang
albertkhang

Reputation: 701

By default FileWrite.append() is synchronized.

View in Writer.java.

enter image description here

Upvotes: 1

Jean Logeart
Jean Logeart

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

Related Questions