JUC源码解析(一)AtomicInteger
来说一个最基本的吧,AtomicInteger
废话不多说,上代码吧
// setup to use Unsafe.compareAndSwapInt for updates
//底层指令的实例引用
private static final Unsafe unsafe = Unsafe.getUnsafe();
//内存首地址的偏移量
private static final long valueOffset;
//静态方法
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
//存放int值,线程可见
private volatile int value;
以上就是AtomicInteger重要的成员变量以及静态方法
1.unsafe 其实就是负责与CAS相关的操作实现,由sun.mic包提供
2.valueOffset的值是变量value的内存首地址的偏移量。,它在AtomicInteger被加载时就被赋值了。
3.value其实就是存放实际值的变量,它被volatile 关键字修饰,说明对于其他线程是可见的。
下面是它的构造器
/**
* Creates a new AtomicInteger with the given initial value.
*
* @param initialValue the initial value
*/
//携带指定值的构造器
public AtomicInteger(int initialValue) {
value = initialValue;
}
/**
* Creates a new AtomicInteger with initial value {@code 0}.
*/
//默认构造器,默认值设置为0
public AtomicInteger() {
}
还有它的常用方法
1.自增
可以看到自增方法通过无限循环不停的尝试修改它的值,直到成功为止
首先获取当前值
然后自增 1
利用原子操作去设定想要的值,如果成功则返回自增后的值,否则继续循环
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
//尝试去修改,直到成功为止
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
//返回自增后的值
return next;
}
}
/**
* Atomically increments by one the current value.
*
* @return the previous value
*/
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
//返回自增前的值
return current;
}
}
同上方法去不断尝试减一
/**
* Atomically decrements by one the current value.
*
* @return the updated value
*/
public final int decrementAndGet() {
//尝试去修改,直到成功为止
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
//返回自减后的值
return next;
}
}
/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
public final int getAndDecrement() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
//返回自减前的值
return current;
}
}
由于是原子操作的,实例值又是线程修改可见的,所以是线程安全的