I have this static class:
public class FileManager{
....
public static void writeOnFile(String something, String filepath){
File f= new File(filepath);
// Append
PrintWriter writer = new PrintWriter(new FileWriter(f, true));
writer.append(something);
}
...
}
that have lots of methods and this one above is one of these.
what I would like to do is that if two callers write to the same file, the writing should be done in mutual exclusion. But when callers write to different files, this doesn't happen (they don't write in mutual exclusion).
This versione below:
public class FileManager{
....
public synchronized static void writeOnFile(String something, String filepath){
File f= new File(filepath);
// Append
PrintWriter writer = new PrintWriter(new FileWriter(f, true));
writer.append(something);
}
...
}
I don't think that's what I want to accomplish. In this case the callers will write in mutual exclusion even if the files they write to are different.
I wanted to ask: this second version:
public class FileManager{
....
public static void writeOnFile(String something, String filepath){
File f= new File(filepath);
// Append
synchronized(f){
PrintWriter writer = new PrintWriter(new FileWriter(f, true));
writer.append(something);
}
}
...
}
would work?. if not, would I have to create an object that contains the filepath of each file in order to use the locks as I would like?