【发布时间】:2020-08-27 18:38:34
【问题描述】:
假设我在 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 或LongAccumulator 执行此操作吗?
我尝试使用这些,但不知道如何使用它们实现复杂的计算。
【问题讨论】:
标签: java multithreading atomic atomicinteger