java - 在本机内存中存储多个字节数组
问题描述
我有固定数量的byte[]
固定长度的字节数组 ( ),我想将它们存储在本机内存中(然后再检索)。但是,我不太确定如何将多个数组直接存储在 MemorySegment 中。
我知道我可能会创建一个大的 MemorySegment 并逐个元素地对其进行初始化,但我认为这种策略会很慢并且会使检索更加麻烦(也许?)。
在 API 文档中,我遇到了 SegmentAllocator 抽象,这似乎解决了我的分配问题,但我不明白如何使用此 SegmentAllocator 检索分配的数据。
try(ResourceScope scope = ResourceScope.newConfinedScope()){
byte[] data = objToByteArray(someClass.getDeclaredConstructor().newInstance()); //suppose data is always of constant length
SegmentAllocator alloc = SegmentAllocator.arenaAllocator(numOfArrays* data.length, scope);
for(int i = 0; i < numOfArrays; i++){
alloc.allocateArray(MemoryLayouts.JAVA_BYTE, data);
data = objToByteArray(someClass.getDeclaredConstructor().newInstance());
}
//how can I access the arrays in alloc?
}catch(Exception e){
e.printStackTrace();
}
有没有办法访问 SegmentAllocator 中的数据,或者是否有不同的方法来解决我的问题?
解决方案
看来您在这里要做的是将这些字节数组端到端复制到某个内存段中。
您应该首先分配一个大内存段,在循环中将其切片,然后一次将一个字节数组复制到一个切片中:
try (ResourceScope scope = ResourceScope.newConfinedScope()) {
byte[] data = objToByteArray(someClass.getDeclaredConstructor().newInstance()); //suppose data is always of constant length
long stride = data.length;
// allocate segment
MemorySegment segment = MemorySegment.allocateNative(numOfArrays * stride, scope);
// copy arrays to segment
for (int i = 0; i < numOfArrays; i++) {
MemorySegment slice = segment.asSlice(i * stride, stride);
slice.copyFrom(MemorySegment.ofArray(data));
data = objToByteArray(someClass.getDeclaredConstructor().newInstance());
}
// read arrays back
for (int i = 0; i < numOfArrays; i++) {
MemorySegment slice = segment.asSlice(i * stride, stride);
data = slice.toByteArray();
System.out.println(Arrays.toString(data));
}
} catch (Exception e) {
e.printStackTrace();
}
(另外,FWIW,您最终会在填充循环的最后一次迭代中创建一个从未实际使用过的额外字节数组)。
推荐阅读
- c - C分配问题:将十进制数转换为位的函数
- javascript - 为什么 getElementById 找不到我的 ReactJs 按钮
- rust - 使用 None 值打开 HashMap 时出现恐慌
- python - 如何解决错误:for i in range(len(val)): TypeError: object of type 'NoneType' has no len() ,这可能很傻
- docker - 如何使用 Certbot 为 xampp docker 安装 ssl 证书?
- python - 如何将 matplotlib fill_between 用于默认 ylim
- google-apps-script - 随机异常 - Google Apps 脚本中的“服务超时:电子表格”
- node.js - mongodb 子文档是否等同于 Firestore 子集合?
- reactjs - 在图表中反应径向渐变填充
- javascript - 对象及其字段的奇怪 console.log 行为