假设我在 Java 中有以下类:
class Record {
String name;
double count;
long repeat;
public Record(String name){
this.name = name;
}
public synchronized void update(Record other){
this.count = (other.count * other.repeat + this.count * this.repeat)/(other.repeat + this.repeat);
this.repeat = this.repeat + other.repeat;
}
现在我有一张此类记录的地图ConcurrentHashMap<String, Record> recordConcurrentHashMap;
我想创建一个线程安全的正确更新函数。
目前我已经这样做了:
static ConcurrentHashMap<String,Record> recordConcurrentHashMap;
public static void updateRecords(Record other){
Record record = recordConcurrentHashMap.computeIfAbsent(other.name, Record::new);
record.update(other);
}
我必须保持update
函数同步以实现正确性。
我可以在不synchronized
使用LongAdder
or的情况下执行此操作LongAccumulator
吗?
我尝试使用这些,但无法弄清楚如何使用它们实现复杂的计算。