java - max 的线程安全实现

标签 java thread-safety java.util.concurrent

我需要为 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/

相关文章:

c++ - 线程同步 - 微妙的问题

java - Java中锁定一个类的所有实例

java - 无法在 Selenium 中按 ID 定位元素

java - 无需浏览器的 Google OAuth 2.0 登录

java - 在模块类中发现重复的类

java - 如何同时修改 Vector

java - LMAX干扰者: How to control the speed of producers?

java - 如何在不使用泛型的情况下限制 ArrayList 的元素

c# - 背景音轨就绪无法正常工作 Windows Phone 8

java - Java中多线程生成唯一素数