我们使用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();
}
}
所以我认为我们可以使用_total
轻松替换LongAdder
,但是因为_current.addAndGet(delta)
LongAdder
不能很好地替代LongAdder
,我们也无法做到“_max”值的cas操作。
是否有基于this
或类似可扩展无锁构造收集此类统计信息的良好算法?
实际上,正如我所问,我们的统计数据通常会更新6到10个AtomicLongs。如果我们无论如何都看到争用,那么抓住一个锁并更新6到10个正常长度可能会更好吗?
答案 0 :(得分:3)
你不想要LongAdder
,但LongAccumulator
在这里:你想要new LongAccumulator(Math::max, Long.MIN_VALUE)
,这在这里是正确的。 LongAdder
是LongAccumulator
的特例。