问题描述
假设我在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
来做到这一点吗?
我尝试使用它们,但无法弄清楚如何使用它们实现复杂的计算。
解决方法
不,您不能,当然不能。
您可能会考虑做的事情–避免使用synchronized
–是使Record
不变且不可修改,并做类似的事情
class Record {
final String name;
final double count;
final long repeat;
public Record(String name){
this.name = name;
}
private Record(String name,double count,long repeat) {
this.name = name; this.count = count; this.repeat = repeat;
}
public Record combine(Record other){
return new Record(
name,other.count * other.repeat + this.count * this.repeat)
/(other.repeat + this.repeat),repeat + other.repeat);
}
}
public static void updateRecords(Record other){
Record record = recordConcurrentHashMap.merge(
other.name,other,Record::combine);
}