AQS source parsing (a) -AtomicBoolean source parsing

  • The basic categories:
  • Array type:
    • AtomicIntegerArray
    • AtomicLongArray
    • AtomicReferenceArray

Introduction

Because in multithreaded conditions, if you modify the shared variables likely to cause data inconsistencies, so for shared variables we need to ensure the security thread has the following ways:

  1. Use lockor synchronizedsynchronize shared variables
  2. CAS is used to modify variables methods to ensure atomicity operation

The latter class is based on the CAS modify atomic.

The principle

  1. Converting the boolean true to inttype indicates: 1 represents 0 represents false true
  2. When initialized in the class to get the value of the memory address
  3. Calling Unsafe.compareAndSwantmethod changes the underlying principle of CAS values (CPU instruction in cmpxchg)

Feature

  1. Based on CAS achieve thread safety
  2. Implements Cloneablethe interface, be cloned
  3. It implements Serializablethe interface, support serialization transmission

Source resolve

Member variables

    private static final long serialVersionUID = 4654671469794556979L;
    // setup to use Unsafe.compareAndSwapInt for updates
    //使用unsafe类进行cas
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    //获取该值得偏移量(内存中的地址)
    private static final long valueOffset;
    /**
     * 内部使用int来做boolean的设置
     * 默认为0
     */
    private  volatile int value;
  1. serialVersionUID: Sequence ID-
  2. unsafe: Atomic core class is class, for performing low-level, the operation of the memory, all internal nativemethods
  3. valueOffset: Memory offset address field value
  4. value: True value, 1 represents true 0 represents false, use volatileto ensure visibility of memory

Class initialization process

    static {
        try {
           //返回对象成员属性在内存地址相对于此对象的内存地址的偏移量
            valueOffset = unsafe.objectFieldOffset
                (AtomicBoolean.class.getDeclaredField("value"));
        } catch (Exception ex) { throw new Error(ex); }
    }

The main memory is to get value worth offset by unsafe methods

Member method

get()

Gets the boolean variable

    /**
     * 返回当前值
     */
    public final boolean get() {
        return value != 0;
    }

boolean compareAndSet(boolean expect, boolean update)

Assignment, there may be value after comparing the situation before the assignment failure

     /*
      * 只有当期待的值为expect的时候才会更新相关值
      *  1. 期待的值等于现在值,则成功赋值,返回true
      *  2. 期待的值不等于现在的值,则赋值失败,则返回false
      */
    public final boolean compareAndSet(boolean expect, boolean update) {
        int e = expect ? 1 : 0;
        int u = update ? 1 : 0;
        return unsafe.compareAndSwapInt(this, valueOffset, e, u);
    }
  1. Converting an int boolean
  2. Call to compareAndSwapIntbe assigned CAS
  3. Returns true for success, false indicates failure

boolean getAndSet(boolean newValue)

比较前值后进行赋值,用的相对较多

    public final boolean getAndSet(boolean newValue) {
        boolean prev;
        do {
            prev = get();
        } while (!compareAndSet(prev, newValue));
        return prev;
    }
  1. 先获取之前值
  2. 在调用循环compareAndSet进行CAS赋值

void set(boolean newValue)

无条件设置值,用的相对较少

    public final void set(boolean newValue) {
        value = newValue ? 1 : 0;
    }

void lazySet(boolean newValue)

也是赋值操作,该操作会让Java插入StoreStore内存屏障,避免发生写操作重排序

public final void lazySet(boolean newValue) {
    int v = newValue ? 1 : 0;
    unsafe.putOrderedInt(this, valueOffset, v);
}

总结

  1. 该类是原子性boolean类,是线程安全的
  2. 该原子类的核心操作都是基于Unsafe类
  3. CAS普遍会产ABA问题

Guess you like

Origin www.cnblogs.com/lonecloud/p/11392032.html