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:
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.
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.
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.
open
, read
, write
(they are terribly slow, because the cpu has to do context switching if you are calling a system callOne drawback however is that you should save your memory-mapping back to disk from time to time. Imagine yourself doing some highly complicated operations in RAM for hours and all of a sudden there's a black out - all information is lost.
There are number of advantages of using Memory mapped File in Java. some of them are:
In addition to the above, the big disadvantage that comes with Memory Mapped File feature of java.nio Java is that if the request page is not in RAM, it results in page fault. so if you are doing append after some initial read/write in the middle of the file, it could possibly result in page fault and that will cause the portion of file to be loaded into memory and I/Os will perform faster afterwards.
Refer this link for more details: 10-Things-to-Know-about-Memory-Mapped-File-in-Java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With