FileChannel Force Fsync Durability
Append to a log through FileChannel and call force(true) so data and metadata reach the device before the caller returns, surviving a process crash.
Code
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class DurableAppend {
public static void main(String[] args) throws IOException {
Path log = Path.of("audit.log");
// APPEND 打开:每次 write 都在文件末尾推进
try (FileChannel channel = FileChannel.open(log,
StandardOpenOption.CREATE, StandardOpenOption.WRITE,
StandardOpenOption.APPEND)) {
ByteBuffer entry = ByteBuffer.wrap("order=1001 approved\n".getBytes());
while (entry.hasRemaining()) {
channel.write(entry);
}
// force(true):数据 + 元数据一起刷到存储设备,进程崩溃后日志仍在;
// force(false) 只刷数据,大小等元信息不保证落盘
channel.force(true);
}
System.out.println("size after fsync: " + Files.size(log));
System.out.println(Files.readString(log).strip());
Files.deleteIfExists(log);
}
}How it works
Count the class DurableAppend as the entire surface area of FileChannel Force Fsync Durability.
Iteration happens inside while (entry.hasRemaining()) — everything outside it runs once. No finally block here — resources declared in the try header close themselves in reverse order.
Putting it to use
Output lines are prefixed (size after fsync:), making each step’s effect easy to spot.
Core lines
ByteBuffer entry = ByteBuffer.wrap("order=1001 approved\n".getBytes());
Path log = Path.of("audit.log");
Files.deleteIfExists(log);
Interactive Tools for This Topic
FAQ
- What does FileChannel Force Fsync Durability print when run?
- Run it as a complete program — the output lines carry labels such as `size after fsync:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.