开发者

Behavior of the FileChannel to RandomAccessFile

开发者 https://www.devze.com 2023-01-21 07:55 出处:网络
I have one use-case where my multiple threads are writing data to same file channel (pooled), and each thread has offset in the file from where they can start writing till the length of the data to be

I have one use-case where my multiple threads are writing data to same file channel (pooled), and each thread has offset in the file from where they can start writing till the length of the data to be written. So when I ask the file channel from pool it will open the channel in "开发者_开发问答rw" mode if it already not opened and will return that file channel (the opened file might be fresh file i.e. size = 0), else it will return cached channel. Problem is that thread might write data in no particular, that means a thread with offset 1,000,000 might start writing before thread with offset 0. Consider I opened a fresh file (size = 0), and thread with offset = 1,000,000 starts writing data (using write(buffer, position) API) before thread with offset = 0.

My first question: Is this allowed at all, or I will get some exception Secondly if it allowed: What is guarantee that my data is correctly written. Third. When my (offset = 1,000,000) is done with writing to file, what will be the content in empty space (0-999,999). How operating system will allocate this intermediate space?


Without actually trying what you're describing, here's an educated guess:

First question: FileChannel is thread safe, and is documented to expand the file size as needed ("The size of the file increases when bytes are written beyond its current size"), so I would think this would be allowed.

Second question: There is no guarantee that your data is correctly written; that's entirely dependent on your skill as a programmer. :)

Third question: I'd expect the byte content of the "empty space" would be OS dependent, but you could write a simple program to test this easily enough.

0

精彩评论

暂无评论...
验证码 换一张
取 消