Unsafe.compareAndSwapInt()方法解读
代码:
/** * Atomically update Java variable to x if it is currently * holding expected. * @return true 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的思想,及比较并交换。用于保证并发时的无锁并发的安全性。