CAS
CAS(Compare-and-Swap),即比较并替换,是一种乐观锁技术,在并发算法时常用到的技术
AtomicInteger 中cas的应用
value 需要用volatile修饰,保证可见性
public class AtomicInteger extends Number implements java.io.Serializable {
private volatile int value;
public final int get() {
return value;
}
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
}
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
调用JNI本地方法
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
比较内存值与当前值是否一致,如果一致,则将内存当前的值替换为修改值,如果不一致放弃修改,则重新获取内存值,循环重试操作
if (this == expect) {
this = update
return true;
} else {
return false;
}
CAS 算法在ConcurrentLinkedQueue中的应用
它必须先获取尾节点,然后设置尾节点的下一个节点为入队节点,但这时可能有另外一个线程插队了,那么队列的尾节点就会发生变化,这时当前线程要暂停入队操作,然后重新获取尾节点。让我们再通过源码来详细分析下它是如何使用CAS算法来入队的。
public boolean offer(E e) {
if (e == null) throw new NullPointerException();
//入队前,创建一个入队节点
Node</e><e> n = new Node</e><e>(e);
retry:
//死循环,入队不成功反复入队。
for (;;) {
//创建一个指向tail节点的引用
Node</e><e> t = tail;
//p用来表示队列的尾节点,默认情况下等于tail节点。
Node</e><e> p = t;
for (int hops = 0; ; hops++) {
//获得p节点的下一个节点。
Node</e><e> next = succ(p);
//next节点不为空,说明p不是尾节点,需要更新p后在将它指向next节点
if (next != null) {
//循环了两次及其以上,并且当前节点还是不等于尾节点
if (hops > HOPS && t != tail)
continue retry;
p = next;
}
//如果p是尾节点,则设置p节点的next节点为入队节点。
else if (p.casNext(null, n)) {
//如果tail节点有大于等于1个next节点,则将入队节点设置成tair节点,更新失败了也没关系,因为失败了表示有其他线程成功更新了tair节点。
if (hops >= HOPS)
casTail(t, n); // 更新tail节点,允许失败
return true;
}
// p有next节点,表示p的next节点是尾节点,则重新设置p节点
else {
p = succ(p);
}
}
}
}
retry:标记位置,内层循环continue后直接跳到外层开始执行了
复制链接,在浏览器打开
tomcat源码解析
https://study.163.com/course/introduction/1209535854.htm
Springmvc源码解析
https://study.163.com/course/introduction/1209536851.htm