-
(1) 原子变量比锁性能更高
(2) 原子变量支持volatile的语义
-
示例
@ThreadSafe public class CasNumberRange { @Immutable private static class IntPair { // INVARIANT: lower <= upper final int lower; final int upper; public IntPair(int lower, int upper) { this.lower = lower; this.upper = upper; } } private final AtomicReference<IntPair> values = new AtomicReference<>(new IntPair(0, 0)); public int getLower() { return values.get().lower; } public int getUpper() { return values.get().upper; } public void setLower(int i) { while (true) { IntPair oldv = values.get(); if (i > oldv.upper) { throw new IllegalArgumentException( "Can't set lower to " + i + " > upper"); } IntPair newv = new IntPair(i, oldv.upper); if (values.compareAndSet(oldv, newv)) { return; } } } public void setUpper(int i) { while (true) { IntPair oldv = values.get(); if (i < oldv.lower) { throw new IllegalArgumentException( "Can't set upper to " + i + " < lower"); } IntPair newv = new IntPair(oldv.lower, i); if (values.compareAndSet(oldv, newv)) { return; } } } }
这个示例中使用了不可变对象IntPair, 用AtomicReference和IntPair保存状态, 并通过使用compareAndSet, 当set时如果值被其他线程修改, 那就返回false进行下一轮循环, 避免了竞态条件
-
锁与原子变量的性能比较
(1) 低竞争条件下, 原子变量性能更好
(2) 高竞争条件下, 锁更好
(因为高竞争条件下, 当原子变量的一次compareAndSet操作失败时, 会重复while循环, 没有缓解竞争; 而锁的方式会导致一些线程被挂起减少了竞争)
chapter15_原子变量与非阻塞同步机制_3_原子变量类
最新推荐文章于 2025-07-02 23:13:28 发布