I am struggling to see the benefits of the memory mapped file (buffer) in Java. here is how I see the approach in practice:
We map chunks of file into main memory and deal with any writes/reads directly in memory, leaving OS to do the job of persisting the file into disk.
Now, I wanted to contrast this with regular I/O and a few scenarios:
- Appending into a file
In order to map the file into mem I have to read it in as a whole, to make overall modifications. The buffer size is the size of a file initially (let's say I do not know how much data I am about to write into the file). Now, in order to append to the file, I cannot do that, because the buffer is of limited size. So the most basic operation seems impossible to me. Also, reading in the whole file to append a small portion seems rather wasteful. So I guess regular I/O performs better in this scenario.
- Persisting changes
In order to persist the changes i still need to flush them. Therefore, if I don't do this periodically I might have lost the changes in the main memory. This is the same idea with regular I/O streams, so no gain here either.
- Random changes
This is where I can see this to work - replacing n bytes with other n bytes. Nevertheless, this seems rather unusual operation to have m characters being replaced by exactly m characters. we would rather have Hello and replace it with Hi. But we have a filled, fixed sized buffer, so that is not easy... Besides, it reminds me of RandomAccessFile with a better performance.
Probably most of what I wrote is nonsense, but I will be happy to be told so, as for me atm the MemoryMappedBuffer seems hard and cumbersome (or even impossible) to use.
Buffer- even if the amount is greater than your main memory (or greater than aBuffercould be at all). But apart from that (and as aoeu pointed out) there are other possible benefits, even for really "file-oriented" operations (mainly: peformance). - Marco13