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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java JUC之Atomic系列12大
- 下一篇: 认识JVM--第一篇-对象分配回收算法