I have some code like the following that I’m running in a debugger in Eclipse:
FileOutputStream fstream = new FileOutputStream(new File("foo"));
byte[] ba = someBytes();
fstream.write(bytes);
// tried with and without the following two lines. no difference
// fstream.flush();
// fstream.getFD().sync();
fstream.close();
When I step through this code in the Eclipse debugger, the file does not exist just after fstream.close() is called (verified via file.exists() from another File object created with the same path, as well as looking for the file in a bash shell).
I assume this is some kind of race condition, but I haven’t been able to find what’s going on. I tried adding fstream.flush() and fstream.getFD().sync(), per another StackOverflow question, but this did not help.
The ultimate symptom of this is that some test cases fail somewhat non deterministically. The behavior appears the same for consecutive identical runs, either with debugging or without, but if I change the breakpoints in the debugger, the behavior can change. I believe it usually/always works when I’m running the code outside of the debugger, but it’s troubling that the same code can fail inside of a debugger.
What could be happening here? Is there a good way to make sure the file is written when I think it is?
**UPDATE: I figured out a little of what is going on. The following hack forces the file to be written:
fstream.close();
fstream = new FileOutputStream(file, true);
This is a hack, but seems to force the OS to finish its writing.
This seemed to be an issue with the Eclipse debugger. The hack I mentioned in my edit is the only way I found to force the expected behavior.