线程安全实现max

Tib*_*ssy 23 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这个实现是否正确?我正在使用java.util.concurrent,因为我相信它会比简单快synchronized.是否有其他/更好的方法来实现这一点?

Jon*_*eet 12

我认为这是正确的,但为了清晰起见,我可能会重写一点,并且肯定会添加评论:

private void updateMax(long sample) {
    while (true) {
        long curMax = max.get();
        if (curMax >= sample) {
            // Current max is higher, so whatever other threads are
            // doing, our current sample can't change max.
            break;
        }

        // Try updating the max value, but only if it's equal to the
        // one we've just seen. We don't want to overwrite a potentially
        // higher value which has been set since our "get" call.
        boolean setSuccessful = max.compareAndSet(curMax, sample);

        if (setSuccessful) {
            // We managed to update the max value; no other threads
            // got in there first. We're definitely done.
            break;
        }

        // Another thread updated the max value between our get and
        // compareAndSet calls. Our sample can still be higher than the
        // new value though - go round and try again.
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:通常我至少首先尝试同步版本,只有当我发现它导致问题时才会使用这种无锁代码.


lor*_*zop 10

从Java 8开始,LongAccumulator已经推出.建议为

当多个线程更新用于收集统计信息但不用于细粒度同步控制的目的的公共值时,此类通常优于AtomicLong.在低更新争用下,这两个类具有相似的特征.但在高争用的情况下,这一类的预期吞吐量明显更高,但代价是空间消耗更高.

您可以按如下方式使用它:

LongAccumulator maxId = new LongAccumulator(Long::max, 0); //replace 0 with desired initial value
maxId.accumulate(newValue); //from each thread
Run Code Online (Sandbox Code Playgroud)


小智 6

使用 Java 8,您可以利用函数式接口和简单的 lamda 表达式来解决这个问题,只需一行代码,无需循环:

private void updateMax(long sample) {
    max.updateAndGet(curMax -> (sample > curMax) ? sample : curMax);
}
Run Code Online (Sandbox Code Playgroud)

该解决方案使用该updateAndGet(LongUnaryOperator)方法。当前值包含在curMax并使用条件运算符执行简单测试,如果样本值大于当前最大值,则用样本值替换当前最大值。