如果内容有错误或者您有不同的见解,请关注我。想要思维导图的小伙伴们记得留言哦。
项目源码以及脑图链接地址:《https://mp.weixin.qq.com/s/V5gfnOBYQJw_6lvmi1oQSQ》
/**
* An {@code int} value that may be updated atomically. See the
* {@link VarHandle} specification for descriptions of the properties
* of atomic accesses. An {@code AtomicInteger} is used in
* applications such as atomically incremented counters, and cannot be
* used as a replacement for an {@link java.lang.Integer}. However,
* this class does extend {@code Number} to allow uniform access by
* tools and utilities that deal with numerically-based classes.
*
* @since 1.5
* @author Doug Lea
*/
public class AtomicInteger extends Number implements java.io.Serializable
【翻译】一个可以对其原子更新操作的int,可以参考VarHandle的有关原子访问属性的描述的说明,AtomicInteger类型的变量可以在程序中当做原子自增的计数器使用,当然不可替代Integer,虽然不可替代,但是该类继承了Number,一些基于数字的工具和程序类还是可以统一访问。
/*
* This class intended to be implemented using VarHandles, but there
* are unresolved cyclic startup dependencies.
*/
private static final Unsafe U = Unsafe.getUnsafe();
private static final long VALUE = U.objectFieldOffset(AtomicInteger.class, "value");
【翻译】这个类打算用VarHandlers来实现的,但是有循环启动依赖没有解决,就无法使用VarHandlers来实现了。
【解释】这个地方使用的就是Unsafe类VALUE就是之前讨论过的获取一个类的属性的内存地址,返回long型内存地址。
private volatile int value;
整个类都是在操作这个volatile修饰的变量value。
/**
* Atomically sets the value to {@code newValue}
* if the current value {@code == expectedValue},
* with memory effects as specified by {@link VarHandle#compareAndSet}.
*
* @param expectedValue the expected value
* @param newValue the new value
* @return {@code true} if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(int expectedValue, int newValue) {
return U.compareAndSetInt(this, VALUE, expectedValue, newValue);
}
【翻译】如果当前值等于期望值,那么就将VALUE(上面说过这里是内存地址)中存储的值原子地设置为newValue。对内存有什么影响参见VarHandle#compareAndSet方法。
【理解】U.compareAndSetInt(this, VALUE, expectedValue, newValue)方法中的参数(当前类,内存地址,期望值,新值):比较期望值和当前值是否相等,如果相等将新值赋值给这个对象的VALUE内存地址对应的值。
那么也就是说cas操作int只能保证一个变量的原子性操作,但是对于代码块的原子性操作还是需要使用Synchronized,如Synchronized(int a,int b, int c)这种块状操作。
Unsafe中的方法:
/**
* Atomically updates Java variable to {@code x} if it is currently
* holding {@code expected}.
*
* <p>This operation has memory semantics of a {@code volatile} read
* and write. Corresponds to C11 atomic_compare_exchange_strong.
*
* @return {@code true} if successful
*/
@HotSpotIntrinsicCandidate
public final native boolean compareAndSetInt(Object o, long offset,
int expected,
int x);
如果内容有错误或者您有不同的见解,请关注我。想要思维导图的小伙伴们记得留言哦。
项目源码以及脑图链接地址:《https://mp.weixin.qq.com/s/V5gfnOBYQJw_6lvmi1oQSQ》