Is there a way to expand the Java memory-mapped byte buffer such that the new size is reflected back to the mapped file on disk?
A direct byte buffer whose content is a memory-mapped region of a file. Mapped byte buffers are created via the FileChannel. map method. This class extends the ByteBuffer class with operations that are specific to memory-mapped file regions.
Performance: Memory mapped writing is often fast as no stream/file buffers are used. OS does the actual file writing, usually in blocks of several kilo bytes at once. One downside would be, unless you're writing sequentially there could be page faults slowing down your program.
The direct buffer memory is the OS' native memory, which is used by the JVM process, not in the JVM heap. It is used by Java NIO to quickly write data to network or disk; no need to copy between JVM heap and native memory.
Memory-mapped files are accessed through the operating system's memory manager, so the file is automatically partitioned into a number of pages and accessed as needed. You do not have to handle the memory management yourself.
No, you will need to adjust the size of the underlying file and recreate the Memory Mapped Byte Buffer.
RandomAccessFile file = new RandomAccessFile(/* some file */);
MappedByteBuffer buffer = file.getChannel().map(MapMode.READ_WRITE, 0, file.length());
// Some stuff happens...
// adjust the size
file.setLength(newLength);
// recreate the memory mapped buffer
buffer = file.getChannel().map(MapMode.READ_WRITE, 0, file.length());
Note: Setting the file length has some slightly odd behaviour. If you write to the file via the map at a specific position that is beyond the end of the file (either using map.position() or map.putX(position, ...)) the values will be appended to the end of the file and not written at the position you expect (on linux at least). If this is undesired behaviour you will need to append data to the file in order to truly grow the file.
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