clarification for synchronized
If I have a class that is writing to a file on a regular basis, and there is a method to change the file (and output stream) then do I need to use synchronize(myFile) in both places? Or is it sufficient to use synchronize(myFile) only in the method that is changing the file? There is such a performance hit on using it in the writing method. If using it in one method blocks the other from using the file at that moment, then that is good because the method to change the file is something that would rarely be called. But I can't risk having the file being changed in the middle of the write method.
This is what I would like to do:
logMessage(String msg){
//write to the file's stream
}
changeFile(File f){
synchronize(myFile){
// change the file and stream
}
}
This is what I have now:
logMessage(String msg){
synchronize(myFile){
//write to the file's stream ** very slow
}
}
changeFile(File f){
synchronize(myFile){
// change the file and stream
}
}
[1606 byte] By [
bsampieri] at [2007-9-26 1:19:27]

changeFile(File f) is supposed to change the file "myFile" to a new file. No, there's not other file objects pointing to the same file. By change file, I mean it's writing to "C:\temp\log1.txt" and I want to close that file and start writing to "C:\temp\log2.txt".
I have a separate object that I'm using as the lock, so, the question is "is this sufficient":
// exception catching code removed for post
Object lock = new Object(); // object for synch
File myFile = new File("C:\temp\log1.txt");
FileOutputStream out = new FileOutputStream(myFile);
writeToFile(String msg) {
out.write(msg.getBytes());
}
changeFile(File f) { // "C:\temp\log2.txt"
synchronized(lock) {
out.close();
myFile = f;
out = new FileOutputStream(myFile);
}
}
or do I need a synchronized block in writeToFile() also?
Speaking of "can other file objects point to the same file"...What would happen if I had 2 FileOutputStreams pointing to the same files? That wouldn't work, right?
No. What if one thread is executing the writeToFile method and another thread tries to change the file? writeToFile could end up trying to write to a closed file, or changeFile could try to close a file that is currently being written to.
If you want only one thread at a time to be doing something with the file, both methods must synchronize on the same object.
My question about two File objects pointing to the same file is now moot, because you have mysteriously changed the code! And I did mean File objects, not FileOutputStream objects.