JLS的内存模型部分(17.4)以合理的方式详细描述了volatile和非volatile读写的语义,以及与某些其他结构(如监视器的进入和退出)的交互。
但是,它并没有完全解释compareAndSwap和lazySet在java.util.concurrent.Atomic*类上的语义。对于compareAndSet,您确实有来自包javadoc的信息
compareAndSet and all other read-and-update operations such as getAndIncrement
have the memory effects of both reading and writing volatile variables. lazySet提供了一些更难以理解的信息:
lazySet has the memory effects of writing (assigning) a volatile variable
except that it permits reorderings with subsequent (but not previous)
memory actions that do not themselves impose reordering constraints with
ordinary non-volatile writes. Among other usage contexts, lazySet may apply
when nulling out, for the sake of garbage collection, a reference that is
never accessed again. 我不清楚的是它们是如何相互作用的。如果向相同的原子值发出CAS (compareAndSet)和lazySet,其中CAS expectedValue与lazySet值不同,那么lazySet是否有可能覆盖lazySet值?
更明确地说,给定两个线程( T1和T2 ),它们在公共AtomicInteger atomic = new AtomicInteger();上操作,如下所示:
static CountDownLatch latch = new CountDownLatch(2);
T1
atomic.lazySet(5); // L1A
latch.countDown();
latch.await();
int val1 = atomic.get();
T2
atomic.compareAndSet(0, 10); // L2A
latch.countDown();
latch.await();
int val2 = atomic.get();在这里,val1 == val2 == 10是一个可能的场景吗?事实上,val1或val2是否可以是10?
闩锁并不是问题的核心--它们只是让两个线程等待另一个线程完成的一种方式,并迫使在每个线程上有趣的lazySet和compareAndSet操作之间发生一个事件,而后面的一个线程读取原子来查看状态(如果没有它们,您肯定至少可以瞬时地看到val2 == 10 )。
发布于 2015-01-27 09:16:47
compareAndSet既是读又是写,因此它确实施加了一个写顺序约束。根据文档,这意味着lazySet写将允许而不是被重新排序。所以不,val1和val2不应该是10岁。
编辑:为了澄清,lazySet本质上所做的是为任何其他也写入同一事物的原子操作而执行原子写入,但对于仅正在读取的其他原子操作,则是非原子操作。
在AtomicInteger lazySet与set上进行的更有用的讨论,最有用的提示是指向添加延迟方法的原始变更集的链接:id=6275329。
https://stackoverflow.com/questions/28164581
复制相似问题