1

These are actually three questions about how to work with memory mapped files. What I did works, but I'm missing an authoritative answer.

I obtain my ByteBuffer like follows:

raf = new RandomAccessFile(file, isReadonly ? "r" : "rw");
channel = raf.getChannel();
buffer = channel.map(mode, 0, channel.size());

For resizing, the following seems to work

raf.setLength(newLength);
channel = raf.getChannel();

without calling raf.getChannel(), but is it really correct?


According to the Javadoc, calling force should flush it (I'm using a local drive). I just wonder how it comes that it declares no IOException and what happens if it fails?


What do I have to close? The RandomAccessFile, the FileChannel, or both of them? Do I have to call some flush or MappedByteBuffer.force before?

maaartinus
  • 44,714
  • 32
  • 161
  • 320

1 Answers1

1

For resizing, the following seems to work

raf.setLength(newLength);
channel = raf.getChannel();

without calling raf.getChannel(), but is it really correct?

Yes. You don't need to reacquire the channel. It's still valid after setLength().

According to the Javadoc, calling force() should flush it (I'm using a local drive). I just wonder how it comes that it declares no IOException and what happens if it fails?

You appear to be talking here about MappedByteBuffer.force(). I cannot explain the designer's choices.

What do I have to close? The RandomAccessFile, the FileChannel, or both of them?

Any of them.

Do I have to call some flush() or MappedByteBuffer.force() before?

There is no flush(). You can call force() if you like, otherwise the changes may be delayed.

user207421
  • 305,947
  • 44
  • 307
  • 483