Video in progress
`write()` returned successfully. Does that mean the data was written to disk? When do you need `force()` and `fsync`?
No. write normally writes only to the OS page cache; if the power goes out, the data can be lost. FileChannel.force(true) (or FileDescriptor.sync()) asks the kernel to push it to the device, and it is an expensive operation.
📖 Answer
The write path goes through several layers: Java buffer → kernel page cache → disk controller cache → platter or flash. flush() empties only the first layer. The kernel writes dirty pages whenever it likes, usually after a few seconds.
try (FileChannel ch = FileChannel.open(journal, CREATE, WRITE, APPEND)) {
ch.write(record);
ch.force(false); // fdatasync: data + the needed metadata
}
force(true) also writes the file's metadata (for example the modification time); force(false) writes only the content and the metadata needed to read it (for example the file length). Often false is enough and faster.
When you need it: a payment or order journal, a WAL you wrote yourself, places where "we told the user OK, so it must not be lost now". When you don't: logs, cache files, exports that can be regenerated.
The price. On an SSD a single fsync takes from hundreds of microseconds to a few milliseconds, on an HDD tens of ms. If you fsync every record, throughput drops to hundreds of records per second. That is why databases do "group commit": they gather several transactions and confirm them with a single fsync.
Two subtle points:
- If you create a new file or
renameone, you need to sync the directory itself too, otherwise after a crash the file name may be gone. In Java, on Linux, this is done by opening the directory withFileChannel.open(dir, READ)and callingforce, but it isn't portable. - The 2018 "fsyncgate": on Linux, after
fsyncreturns an error, calling it again may succeed, but the data is already lost. After that, PostgreSQL started stopping the process on an fsync error. So swallowing anIOExceptionfromforce()with "I'll just retry" is dangerous.
Sign up to mark studied questions and save your progress.