Programming: Atomicity
From wikinotes
Atomicity is when an operation is guaranteed to happen all at once, or not at all.
ex: a database transaction, or an programming language atomic type.
Strategies
Copy-on-Write
A
mv
operation in a filesystem is generally cheap/atomic (change pointer).
- write your fullchangeset to a temp directory
- only if the write is successful,
mv
it to the desired locationA variation on this strategy is sometimes used by firmware.
- Two separate firmware installs are persisted
- When flashing new firmware, the non-used copy is updated
- If it succeeds, the new firmware copy is used (and the old becomes the new update target). otherwise the old copy is used.
Some filesystems (like zfs) do this under the hood.
Double-Write Buffer
Databases like MySQL's innodb use a double-write buffer to guarantee write atomicity.
- In addition to the final datastore, we keep a rolling buffer (the double-write buffer) with a short history of writes.
- Before writing to the datastore, the buffer is written to
- Immediately after writing the buffer, we write to the datastore
When the program is started up, some mechanism is used to verify that the info is sane.
- if the buffer write failed, the (old) datastore value is used
- if the datastore write failed, the (new) buffer write value is copied to the datastore and used