JAVA?????????????CAS????
???????????? ???????[ 2013/11/18 10:47:17 ] ????????
CAS????
????CAS?????compare and set????д??????????set????????????б仯???????????????2???丳???
??????????????????????
????if(a==b) {
????a++;
????}
??????????????????a++??a???????????????a++????????????????????????????????£?a?????????????????????????????????????????CAS???????????????????????
int expect = a;
if(a.compareAndSet(expect??a+1)) {
doSomeThing1();
} else {
doSomeThing2();
}
|
???????????a??????????a++??????С?
?????????????д????a!=expect???a++??????У????????????????a++??????????????????????while???
while(true) {
int expect = a;
if (a.compareAndSet(expect?? a + 1)) {
doSomeThing1();
return;
} else {
doSomeThing2();
}
}
|
?????????????д???????????????????????a++???????????????????????????
???????
????java.util.concurrent.atomic???м???????????????CAS????????AtomicInteger????????????????????????????
public final int getAndSet(int newValue) {
for (;;) {
int current = get();
if (compareAndSet(current?? newValue))
return current;
}
}
|
????getAndSet????JDK????е???????????????????????????????????????????????δ?????????compareAndSet???????compareAndSet??????????
????public final boolean compareAndSet(int expect?? int update) {
????return unsafe.compareAndSwapInt(this?? valueOffset?? expect?? update);
????}
?????????????????????Unsafe???CAS?????????
????????????a++??????????????
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current?? next))
return current;
}
}
|
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11