← 中文资源

简体中文版本

FileChannel force 落盘持久性

FileChannel 追加写入后调用 force(true) 把数据与元数据一起刷到存储设备:进程崩溃后日志仍在;force(false) 只保数据不保元数据。

阅读英文原文

实现说明

底层就是类 DurableAppend。 重复被限制在 while (entry.hasRemaining()) 里——其余代码按顺序各跑一遍。try-with-resources 会在每条退出路径上自动关闭声明的资源。

使用要点

  • 每一步打印都带着自己的标签:size after fsync:。

常见问题

运行「FileChannel force 落盘持久性」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 size after fsync: 这类标签。

核心语句

ByteBuffer entry = ByteBuffer.wrap("order=1001 approved\n".getBytes());
Path log = Path.of("audit.log");
Files.deleteIfExists(log);

代码示例

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);
    }
}