使用 LongAdder 计算统计计数器的最大值?

Using LongAdder to calculate a max value for a statistical counter?

我们使用 AtomicLongs 收集一些统计信息。一些用户看到了关于这些的争论,并建议改用 LongAdder。但是,我看不到我们目前使用 Atomic 计算最大值的方法:

AtomicLong _current, _total, _max;
...

void add(long delta)
{
  long current = _current.addAndGet(delta);
  if (delta>0)
  {
    _total.addAndGet(delta);
    long max = _max.get();
    while (current > max)
    {
      if (_max.compareAndSet(max, current))
        break;
      max = _max.get();
    }
 }

所以我认为我们可以很容易地用 LongAdder 替换 _total,但是因为我们使用 _current.addAndGet(delta) 这对于 LongAdder 来说效果不佳,也不能我们对 `_max' 值进行 cas 运算。

是否有基于LongAdder或类似的可扩展无锁结构来收集此类统计信息的好算法?

实际上,虽然我在问,但我们的统计数据通常会更新 6 到 10 个 AtomicLong。如果无论如何我们都看到争用,是否可以只获取一个锁并更新 6 到 10 个正常多头更好?

你不想要 LongAdder,但这里 LongAccumulator:你想要 new LongAccumulator(Math::max, Long.MIN_VALUE),这在这里做对了。 LongAdderLongAccumulator.

的特例