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 @   r1-12king  阅读(514)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示