Skip to content

Commit 10033d3

Browse files
authored
Merge pull request #2855 from paigeman/main
修复Unsafe CAS的代码仍存在的问题
2 parents ed5f2b7 + c9ffd03 commit 10033d3

1 file changed

Lines changed: 6 additions & 4 deletions

File tree

docs/java/basis/unsafe.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -568,10 +568,12 @@ private void incrementAndPrint(int targetValue) {
568568
return;
569569
}
570570
// 尝试 CAS 操作:如果当前值等于 targetValue - 1,则原子地设置为 targetValue
571-
if (unsafe.compareAndSwapInt(this, fieldOffset, currentValue, targetValue)) {
572-
// CAS 成功后立即打印,确保打印的就是本次设置的值
573-
System.out.print(targetValue + " ");
574-
return;
571+
if (currentValue == targetValue - 1) {
572+
if (unsafe.compareAndSwapInt(this, fieldOffset, currentValue, targetValue)) {
573+
// CAS 成功后立即打印,确保打印的就是本次设置的值
574+
System.out.print(targetValue + " ");
575+
return;
576+
}
575577
}
576578
// CAS 失败,重新读取并重试
577579
}

0 commit comments

Comments
 (0)