看过java.util.concurrent.atomic包里面各个AtomicXXX类实现的同学应该见过lazySet方法,比如AtomicBoolean类的lazySet方法
public final void lazySet(boolean newValue) {
int v = newValue ? 1 : 0;
unsafe.putOrderedInt(this, valueOffset, v);
}
它的底层实现调用了Unsafe的putOrderedInt方法,来看看putOrderedXXX方法的JavaDoc
它的意思是putOrderedXXX方法是putXXXVolatile方法的延迟实现,不保证值的改变被其他线程立即看到
<span><span><span style="font-family:Calibri;font-size:12px;"> /***
* Sets the value of the integer field at the specified offset in the
* supplied object to the given value. This is an ordered or lazy
* version of <code>putIntVolatile(Object,long,int)</code>, which
* doesn't guarantee the immediate visibility of the change to other
* threads. It is only really useful where the integer field is
* <

本文探讨了AtomicXXX类中的lazySet方法,它作为putOrderedXXX的延迟实现,不保证立即可见性。文章指出,虽然volatile变量提供内存屏障确保可见性,但在某些场景下,如在自定义可重入锁实现中,由于锁的获取和释放已经确保了内存交互,使用lazySet可以避免不必要地使用volatile,从而优化性能。
最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



