0

假设我在 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使用LongAdderor的情况下执行此操作LongAccumulator吗?

我尝试使用这些,但无法弄清楚如何使用它们实现复杂的计算。

4

1 回答 1

3

不,你不能,当然不是那些。

你可能会考虑做的——这将避免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);
}
于 2020-08-27T18:45:15.333 回答