AtomicInteger,AtomicBoolean,AtomicReference 落日映苍穹つ 2022-09-10 13:20 144阅读 0赞 #### AtomicInteger的使用 #### public static void main(String[] args) { AtomicInteger atomicInteger = new AtomicInteger(); atomicInteger.getAndIncrement(); atomicInteger.getAndDecrement(); } AtomicInteger的属性 private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; static { try { //valueOffset = AtomicInteger类中的value属性在内存中的偏移量 valueOffset = unsafe.objectFieldOffset (AtomicInteger.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); } } getAndIncrement实现 public final int getAndIncrement() { return unsafe.getAndAddInt(this, valueOffset, 1); } public final int getAndAddInt(Object var1, long var2, int var4) { int var5; do { //var1=AtomicInteger对象,var2=AtomicInteger中value的偏移量 //这里获得AtomicInteger的值 var5 = this.getIntVolatile(var1, var2); //cas:将AtomicInteger的值和var5比较,如果相等,则设置为var5 + 1(这里传入var4等于1)。否则自旋 } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4)); return var5; } #### AtomicBoolean的使用 #### AtomicBoolean atomicBoolean = new AtomicBoolean(); atomicBoolean.getAndSet(true); AtomicBoolean的实现 private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; static { try { valueOffset = unsafe.objectFieldOffset (AtomicBoolean.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); } } private volatile int value; public final boolean getAndSet(boolean newValue) { boolean prev; do { //获得boolean的当前值,根据AtomicBoolean中的value是否等于0返回true或false prev = get(); //把prev设置为新的值,失败自旋 } while (!compareAndSet(prev, newValue)); return prev; } public final boolean compareAndSet(boolean expect, boolean update) { //根据传入的值是true还是false声明变量为1或者0 int e = expect ? 1 : 0; int u = update ? 1 : 0; //cas设置value的值 return unsafe.compareAndSwapInt(this, valueOffset, e, u); } #### AtomicReference的使用 #### AtomicReference atomicReference = new AtomicReference(new Object()); Object oldObject = atomicReference.getAndSet(new Object()); Object newObject = atomicReference.get(); AtomicReference的实现 private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; static { try { valueOffset = unsafe.objectFieldOffset (AtomicReference.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); } } //泛型value private volatile V value; //构造方法设置value public AtomicReference(V initialValue) { value = initialValue; } public final V getAndSet(V newValue) { return (V)unsafe.getAndSetObject(this, valueOffset, newValue); } //var1:AtomicReference对象,var2:value的偏移量,var4新的对象 public final Object getAndSetObject(Object var1, long var2, Object var4) { Object var5; do { //获得value对象 var5 = this.getObjectVolatile(var1, var2); //cas设置value为新对象 } while(!this.compareAndSwapObject(var1, var2, var5, var4)); return var5; }
还没有评论,来说两句吧...