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的思想,及比较并交换。用于保证并发时的无锁并发的安全性。

posted @ 2022-03-28 11:43  r1-12king  阅读(402)  评论(0编辑  收藏  举报