重用内存 MappedByteBuffer

Reusing MemoryMappedByteBuffer

我将文件读入 MappedByteBuffer:

MappedByteBuffer buffer = FileChannel.open(file, StandardOpenOption.READ)
    .map(FileChannel.MapMode.READ_ONLY, 0, Files.size(file))
    .load();

并将其写入 OutputStream:

Channels.newChannel(getOutputStream())
    .write(buffer);

但是,我只能做这一个,大概是因为ByteBuffer "current location"在缓冲区的末尾。

那么,对于我希望让多个线程使用此内存映射文件这一事实,推荐的处理方式是什么?

使用rewind():

Rewinds this buffer. The position is set to zero and the mark is discarded.

Invoke this method before a sequence of channel-write or get operations, assuming that the limit has already been set appropriately.

Channels.newChannel(getOutputStream()).write(buffer);
buffer.rewind();
// ...
Channels.newChannel(getOutputStream()).write(buffer);
buffer.rewind();
// ...

请注意ByteBuffer不是线程安全结构。

您最好的选择可能是为每个线程制作一份 ByteBuffer 的副本,以便可以同时读取它:

// in thread 1
ByteBuffer duplicate = buffer.duplicate();
// ...
// in thread 2
ByteBuffer duplicate = buffer.duplicate();
// ...