Home > OS >  A safest way to replace an important file: copyTo vs rename vs... in Java/Kotlin
A safest way to replace an important file: copyTo vs rename vs... in Java/Kotlin

Time:05-18

My app needs to update(replace) a very important file A from a pending one P. There are several ways to do it, such as:

  1. Remove A and Rename P to A
  2. CopyTo A with overwrite option
  3. ...

Is there a way that is less error-prone in several situations, including power failure of the device? Thanks,

CodePudding user response:

I think the key word you're aiming for here is atomic. That means that this needs to be an all-or-nothing action: either it should all succeed (the old file is removed and the new one renamed into its place), or nothing should change (and the program can safely retry or report failure or whatever without losing any data).

Guaranteeing atomicity is a hard problem (especially in the face of power outage, hardware failure, &c), but hardware and OSs and filesystems (and database servers and other systems) have come a long way and many of them can do it in all but the most extreme conditions.

It's not something that Kotlin itself can arrange. But the Java stdlib does provide an atomic move (if the platform supports it), and so if you're using Kotlin/JVM you can call Files.move() and provide both the REPLACE_EXISTING and ATOMIC_MOVE options.

(If that can't guarantee atomicity, it will throw an AtomicMoveNotSupportedException, and you can either give up, or fall back to a less-safe approach if needed.)

I think this is probably the best you can reasonably do in Kotlin (without investing in native code, or expensive software or hardware).

See this question, and in particular this answer from which the above call was shamelessly cribbed. And this question also mentions its use in Kotlin.

CodePudding user response:

This is an extremely broad question and doesn't really have anything to do with java or kotlin, the behavior of file system operations in case of failure is purely platform-dependent. Not to mention the answer would also be influenced by what kind of failure you're trying to protect from, what level of safety guarantees you want, etc.

That being said 2. will be less safe in most situations as it is (in general) more likely to lead to corruption of A. Either renaming A or removing it and then renaming P is usually gonna be 'safer' since there is less chance of an intermediate state on common filesystems, since no changes are made to the data itself due to the way most common filesystems handle that operation.

But again, this is not the right place for this question and should at the very least be asked in regards to your filesystem and operating system and with a more specific failure model in mind.

  • Related