我需要为 Web 服务器实现全局对象收集统计信息。我有 Statistics
单例,它有方法 addSample(long sample)
,随后调用 updateMax
。这显然必须是线程安全的。我有这种方法可以更新整个统计数据的最大值:
AtomicLong max;
private void updateMax(long sample) {
while (true) {
long curMax = max.get();
if (curMax < sample) {
boolean result = max.compareAndSet(curMax, sample);
if (result) break;
} else {
break;
}
}
}
这个实现是否正确?我正在使用 java.util.concurrent,因为我相信它会比简单的 synchronized
更快。有没有其他/更好的方法来实现这个?
最佳答案
从 Java 8 开始,LongAccumulator已介绍。 建议为
This class is usually preferable to AtomicLong when multiple threads update a common value that is used for purposes such as collecting statistics, not for fine-grained synchronization control. Under low update contention, the two classes have similar characteristics. But under high contention, expected throughput of this class is significantly higher, at the expense of higher space consumption.
您可以按如下方式使用它:
LongAccumulator maxId = new LongAccumulator(Long::max, 0); //replace 0 with desired initial value
maxId.accumulate(newValue); //from each thread
关于java - max 的线程安全实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6072040/