According to this question, small file appends on Windows are atomic.
I am trying to leverage this in Scala / Java to avoid locking when appending a small int to a file.
I am finding that writes using FileOutputStream(..., true)
from multiple threads are being interleaved, even though the question linked above suggests that they should be atomic.
A test harness for this in Scala can be found on my github
The key code is:
def invoked(id: Int, path: String) = {
val writer = new FileOutputStream(path, true)
val bytes = (id.toString + ';').getBytes(Charset.defaultCharset())
writer.write(bytes)
writer.close()
}
... I was hoping that "invoked" would be thread-safe without locking.
The same Java/Scala code achieves atomic file appends on Linux (as per this question small file appends are atomic on POSIX), so the difference seems to be in the native implementations of FileOutputStream
.
Perhaps FileOutputStream
is not passing the correct flags to Windows? Does anyone know how to make this work? Will I have to write a JNI DLL to get this to work, or is there a way I can do this with Java's standard libraries?