gpt4 book ai didi

java - 重用内存 MappedByteBuffer

转载 作者:行者123 更新时间:2023-12-01 11:05:10 24 4
gpt4 key购买 nike

我将文件读入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“当前位置”位于缓冲区的末尾。

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

最佳答案

使用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();
// ...

关于java - 重用内存 MappedByteBuffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33040045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com