A Faster Volatile

在java中使用volatile修饰变量,在某些多线程读写情况下可以避免显示加锁,但是volatile实现的原理是在读写volatile变量的上下文中添加内存屏障,禁止cpu对指令进行调序优化,并且保证,如果一个线程写了这个volatile变量,那么在写之前,这个变量肯定能获得其最新值,在写之后其他线程就能立即获得其最新值。


从中可以看到,对volatile变量进行读写的cost还是比较大,有没有更快的方法?


用java自带的原子类型代替volatile,

使用其中的lazySet更新变量,其他线程在几个纳秒之后才能知道更新,而不是立即,避免了较多的通信

也就是说,如果调用get,可能获得是之前的旧值,一,这概率太低,二,对于读线程而言,获得一个旧值,在语义上也没有错误。

本人推测,如果其他读线程在调用lazySet的时候,肯定是在最新值的基础上更改的。


http://robsjava.blogspot.com/2013/06/a-faster-volatile.html

One of the methods in AtomicReference is lazySet, under the covers it calls unsafe.putOrderedObject

public final void lazySet(V newValue) {
           unsafe.putOrderedObject(this, valueOffset, newValue); 
}


Unsafe.putOrderedObject is useful for tuning ultra low latency code. It allows us to create non-blocking code with guaranteed writes. These writes will not be re-orderd by instruction reordering. Under the covers it uses the faster store-store barrier, rather than the the slower store-load barrier, which is used when doing a volatile write.

This performance improvement comes at a cost, as the writes may not immediately be visible to other threads. However, in practice, these writes usually become visible to the other threads within a few nanoseconds. Since this approach does not stall the bus, it usually performs better.

StoreStore Barrier

A StoreStore barrier effectively prevents reordering of stores performed before the barrier with stores performed after the barrier.

StoreLoad Barrier

A StoreLoad barrier ensures that all stores performed before the barrier are visible to other processors, and that all loads performed after the barrier receive the latest value that is visible at the time of the barrier.


你可能感兴趣的:(A Faster Volatile)