java线程安全实现_java – 线程安全的实现最大

本文探讨了在多线程环境下使用无锁编程更新最大值的策略。通过`compareAndSet`原子操作,确保在并发场景下正确更新全局最大值。首先尝试同步版本,如果发现性能问题,再采用无锁实现。这种方法避免了锁的开销,提高了并发性能。
摘要由CSDN通过智能技术生成

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

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.

}

}

编辑:通常我至少会先尝试同步版本,只有当我发现这是一个问题的时候,只有这样的无锁代码.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值