I have a Java server that appends certain information from multiple clients to a single file. So I am creating a FileWriter
with append=true, and a PrintWriter
with autoFlush=true. However, when I monitor (E.g., using the tail command) the file, the content is not immediately written out, usually there is 10-30 seconds delay. The server is running on Linux with JDK 1.7 64b. Why does autoflush not work here? How to make the data immediately available in the file?
//Create appendable FileWriter, and autoflushable PrintWriter
PrintWriter pw = new PrintWriter(new FileWriter(file, true), true);
... ...
if (save2File) {
//println(String) supposed to flush the content
pw.println(getEventOutput(event));
// adding flush still not working!
pw.flush();
}
Here is the code to reproduce the issue on. On Linux there is a noticeable delay (~1-2s) after the app output the line, and before the line is viewable in another terminal (using tail -f). On windows, it seems the output is pretty fast (faster than I am able to refresh the file in Notepad++)
public static void main(String[] args) throws IOException,
InterruptedException {
long time = 5000;
File file = new File("xyz.test");
PrintWriter pw = new PrintWriter(new FileWriter(file, true), true);
for (int i = 0; i < 10; ++i) {
pw.println("this is line " + i);
System.out.println("output line " + i);
// Thread.sleep(time);
System.in.read();
}
System.in.read();
}
Update 2012-12-04:
I think I find the root cause of the problem. It's actually the async /nfs mount on Linux. The directory the server write file to is mounted as async nfs
... ... nfs vers=3,async,rw,rsize=32768,wsize=32768 0 0
After I switch the file to /tmp, the file appending is immediate now.