[英]Does Java have something similar to C++ Standard Library list comparator for finding an object by a variable value?
[英]Does Java have something similar to c++'s combinable?
我正在使用.parallelStream().forEach()
對數據庫進行大量寫入操作,但也想保留我已寫入的行數。
現在,我有一個java.util.concurrent.atomic.AtomicInteger
來跟蹤計數,但是我想使用類似於c ++的combinable<>
。
在本文中 ,有一個使用combinable<>
的示例:
#include <iostream>
#include <cstdint>
#include <ppl.h>
using namespace Concurrency;
const int max_sum_item = 1000000000;
int main()
{
combinable<uint64_t> part_sums([] { return 0; });
parallel_for(0, max_sum_item,
[&part_sums] (int i)
{
part_sums.local() += i;
}
);
uint64_t result = part_sums.combine(std::plus<uint64_t>());
if (result != uint64_t(499999999500000000))
throw;
}
Java中是否有一個等效的combinable<>
類?
Java代碼段:
AtomicInteger totalRows = new AtomicInteger(0);
...
myList.parallelStream().forEach(
... // write to db
totalRows.addAndGet(rowsWritten);
...
);
print(totalRows.get());
尋找類似的東西:
Combinable<int> totalRows = new Combinable<>(0);
...
myList.parallelStream().forEach(
... // write to db
totalRows = rowsWritten;
...
);
print(totalRows.combine());
編輯:根據@ zero323,Spark中正確的工具將是一個Accumulator
。 我對多線程情況更感興趣,但是atm上沒有非Spark實例。
EDIT2:更新示例(並刪除Spark引用)
Spark中合適的工具將是一個Accumulator
:
Accumulator<Integer> accum = sc.accumulator(0);
myRDD.parallelStream().forEach(
accum.add(1);
);
accum.value();
從工作人員的角度來看,累加器是只寫的,並且只能由驅動程序讀取。 默認情況下,它僅支持Long
, Double
和Float
但是您可以實現自定義AccumulatorParam
以支持其他類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.