问题描述
我面临的任务是我必须将大约 100k 到 200k Pojo
s 转换为 Dto
s。
-
Pojo
是基于用于解析class
文件的.xsd
文件自动生成的.xml
:class Pojo { public long id; public String name; // constructors // getters,setters }
-
Dto
是另一个自动生成的class
,我们正在内部处理应用程序:class Dto { public String name; // constructors // getters,setters }
然后将转换后的 Dto
放入基于 Pojo.getId() % bucketAmount
选择的存储桶中。这些存储桶的行为就像一个粗略的哈希表,我无法用适当的 Map
替换它们,因为在对象转换为 JSON 并存储在文件系统上之前,这种表示只是临时的。
由于数据量和将 Pojo
转换为 Dto
所需的时间,我选择使用 parallelStream()
和一个 atomicreferenceArray
来表示存储桶:
atomicreferenceArray<Set<Dto>> buckets = new atomicreferenceArray<>(bucketAmount);
我目前遇到的问题是,如果不存在以前的值,我不确定如何在 Set
中以原子方式创建新的 atomicreferenceArray
。基于 Pojo.getId() % bucketAmount
,很可能永远不会存在存储桶,因此我不想默认使用空 Set
初始化数组。
我拥有的是以下内容:
pojos.parallelStream().forEach(pojo -> {
// transform pojo to dto
Dto dto = ...;
// compute the bucket id
int bucketId = pojo.getId() % bucketAmount;
// initialize the bucket if absent and add dto to it
buckets.getAndUpdate(bucketId,bucket -> {
if (bucket == null) {
bucket = ConcurrentHashMap.newKeySet();
}
bucket.add(dto);
return bucket;
});
});
但感觉这不是一个合适的解决方案。我正在寻找的是类似于 Map#computeIfAbsent()
的东西,它在 ConcurrentMap
上使用时可确保原子行为。
还是我应该只使用 ConcurrentMap<Integer,Set<Pojo>>
开头?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)