views:

19

answers:

1

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?

+2  A: 

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.

Bill Horvath II
On Linux it would be 0s, and the file would (probably) be sparse -- it would not actually use space for the bytes that you skipped over without writing, until something was actually written there.
Jonathan