Search code examples
javafileioatomic

Create and write a file in one atomic operation on OS level


So I need to create a file then write one line to it and this must be atomic. So that no other process may tinker with the file whilst it is under initialization.
I have one idea, to lock on something different then while the lock is held, do the operations then release the lock to let the other party in. But this is quite tedious, also may be erroneus because creating the lock and acquiring it might be not atomic (I guess). No other way to do it?


Solution

  • I'd suggest you to write temporary file and then rename it to your file. I am not sure this operation is implemented in java as atomic for all operating system but at least on Unix you have a chance because I think it uses the same call as mv that is atomic.

    It will not be truly atomic on windows, I guess. It will be "almost atomic" that is enough for most applications.