RandomAccessFile.close()内部调用FileChannel.force()吗?

时间:2021-09-02 13:29:09

I am using RandomAccessFile to perform some writes to a file as part of a transaction. Before I commit my transaction, I want to be absolutely sure that the data is written to disk. Calling force(boolean) on the RAF's FileChannel appears to provide this guarantee, but is it called implicitly when I close the file, or do I have to call it manually?

我使用RandomAccessFile作为事务的一部分执行对文件的一些写入。在我提交事务之前,我想绝对确保将数据写入磁盘。 RAF的FileChannel上的调用强制(布尔值)似乎提供了这种保证,但是当我关闭文件时它是隐式调用的,还是我必须手动调用它?

Also, does anybody have any insight into what force() actually does, and how far it can be trusted? Is it possible that the OS may report that the data has been written to disk, when in fact it is still sitting in some cache somewhere? To what extent is this OS/HDD/filesystem-dependent?

此外,是否有人能够深入了解force()实际上做了什么,以及它可以信任多远?操作系统是否可能报告数据已写入磁盘,实际上它仍然位于某个缓存中?这个OS / HDD /文件系统在多大程度上依赖?

1 个解决方案

#1


This is completely FS-dependent. But if you do not get an (IO)Exception, you should trust the JVM and commit your transaction. Whether you can trust your FS is the other question. For example, if you use ext4 having delayed allocation activated, you might lose data on a instant power loss even after RandomAccessFile#force(boolean) returned successfully. The JVM relies on the FS-API of your operating system and does not care about the actual implementation and configuration.

这完全取决于FS。但是如果你没有得到(IO)异常,你应该相信JVM并提交你的事务。你是否可以信任你的FS是另一个问题。例如,如果您使用ext4激活了延迟分配,即使在RandomAccessFile#force(boolean)成功返回后,您也可能会在即时断电时丢失数据。 JVM依赖于操作系统的FS-API,而不关心实际的实现和配置。

And yes, you have to call RandomAccessFile#force(boolean) before closing. Whether #close invokes #force is up to the FileChannel's implementation.

是的,你必须在关闭之前调用RandomAccessFile #force(boolean)。 #close是否调用#force取决于FileChannel的实现。

#1


This is completely FS-dependent. But if you do not get an (IO)Exception, you should trust the JVM and commit your transaction. Whether you can trust your FS is the other question. For example, if you use ext4 having delayed allocation activated, you might lose data on a instant power loss even after RandomAccessFile#force(boolean) returned successfully. The JVM relies on the FS-API of your operating system and does not care about the actual implementation and configuration.

这完全取决于FS。但是如果你没有得到(IO)异常,你应该相信JVM并提交你的事务。你是否可以信任你的FS是另一个问题。例如,如果您使用ext4激活了延迟分配,即使在RandomAccessFile#force(boolean)成功返回后,您也可能会在即时断电时丢失数据。 JVM依赖于操作系统的FS-API,而不关心实际的实现和配置。

And yes, you have to call RandomAccessFile#force(boolean) before closing. Whether #close invokes #force is up to the FileChannel's implementation.

是的,你必须在关闭之前调用RandomAccessFile #force(boolean)。 #close是否调用#force取决于FileChannel的实现。