Unsafe.compareAndSwapInt()方法解讀

 代碼:

/**
* Atomically update Java variable to <tt>x</tt> if it is currently
* holding <tt>expected</tt>.
* @return <tt>true</tt> if successful
*/
public final native boolean compareAndSwapInt(Object o, long offset,
                                              int expected,
                                              int x);

此方法是Java的native方法,並不由Java語言實現。

方法的作用是,讀取傳入對象o在內存中偏移量爲offset位置的值與期望值expected作比較。

相等就把x值賦值給offset位置的值。方法返回true。

不相等,就取消賦值,方法返回false。

這也是CAS的思想,及比較並交換。用於保證併發時的無鎖併發的安全性。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章