当前位置:网站首页>Atomicinteger atomic operation class

Atomicinteger atomic operation class

2022-06-11 07:04:00 I will definitely go to Maidang in rainbow sea

️‍ Personal website :code treasure , Welcome to visit
My public number :code treasure , Share your learning resources , Welcome to your attention
Thank you very much for your support and praise

Atomicity

One or more operations Either all of them are executed and the execution process will not be interrupted by any factors , Or they don't do it .

int++ It's not an atomic operation , So when a thread reads its value and adds 1 when , Another thread may modify the original int value , This will cause an error .

Atomic classes

java.util.concurrent This package provides a set of atomic classes . Its basic characteristic is in multithreading environment , When there are multiple threads executing the methods contained in the instances of these classes at the same time , Be exclusive , That is, when a thread enters a method , When executing the instructions , Will not be interrupted by other threads , And other threads are like spinlocks , Wait until the method execution is complete , Then from JVM Select a thread from the waiting queue to enter , It's just a logical understanding .

Atomic classes :AtomicBoolean,AtomicInteger,AtomicLong,AtomicReference

An array of atoms :AtomicIntegerArray,AtomicLongArray,AtomicReferenceArray

Atomic property updater :AtomicLongFieldUpdater,AtomicIntegerFieldUpdater,AtomicReferenceFieldUpdater

solve ABA The atomic class of the problem :AtomicMarkableReference( By introducing a boolean To reflect whether there has been any change in the middle ),AtomicStampedReference( By introducing a int Come to lega to reflect whether there has been any change in the middle )

AtomicInteger principle

public class AtomicInteger extends Number implements java.io.Serializable {
    
    private static final long serialVersionUID = 6214790243416807050L;

    // setup to use Unsafe.compareAndSwapInt for updates
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    static {
    
        try {
    
            
            valueOffset = unsafe.objectFieldOffset
                (AtomicInteger.class.getDeclaredField("value"));
        } catch (Exception ex) {
     throw new Error(ex); }
    }

    private volatile int value;
}

AtomicInteger Class mainly uses CAS (compare and swap) + volatile and native Method to ensure atomic operation , To avoid synchronized The high cost of , Greatly improved execution efficiency .

CAS The principle is to compare the expected value with the original value , If it is the same, update it to a new value .

UnSafe Class objectFieldOffset() A method is a local method , This method is used to get value The memory address of the property , The return value is valueOffset, We can go through this valueOffset visit value attribute .

in addition value It's a volatile Variable , Visible in memory , therefore JVM It can guarantee that any thread can always get the latest value of this variable at any time .

Unsafe Object provides a very low-level , Operating memory 、 Thread method ,Unsafe Object cannot be called directly , Only by reflection .jdk8 Call directly Unsafe.getUnsafe() To obtain the unsafe.

public final int getAndIncrement() {
    
    return unsafe.getAndAddInt(this, valueOffset, 1);
}

//unsafe.getAndAddInt
public final int getAndAddInt(Object var1, long var2, int var4) {
    
    int var5;
    do {
    
        // Get the old value of the shared variable 
        var5 = this.getIntVolatile(var1, var2);
    } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));

    return var5;
}

compareAndSwapInt() Contains three operands :

Memory location (var2)、 The original value of the expected (var5) And the new value ( var5 + var4)

If the value of the memory location matches the expected original value , The processor will automatically update the location value to the new value . Otherwise it will spin until it succeeds .

原网站

版权声明
本文为[I will definitely go to Maidang in rainbow sea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110700055012.html