[JUC source code] Analysis of atomic source code

In the java.util.concurrent.atomic package, there are many atomic operation classes at the beginning of Atomic. When it comes to the commonly used number types in Java, there is basically a corresponding Atomic atomic operation class, as shown in the following figure:
image description
The atomic operation class at the beginning of Atomic is thread-safe in high concurrency scenarios, and we can use it with confidence.

1.AtomicInteger

It is mainly to call the CAS operation of the Unsafe class. The following is part of the source code of AtomicInteger:

public class AtomicInteger extends Number implements java.io.Serializable {
    
    
    
    // 注:value是被volatile修饰的
    private volatile int value;

    // 初始化
    public AtomicInteger(int initialValue) {
    
    
        value = initialValue;
    }
    
    // 得到当前值
    public final int get() {
    
    
        return value;
    }
    
    // 自增 1,并返回自增之前的值    
    public final int getAndIncrement() {
    
    
        return unsafe.getAndAddInt(this, valueOffset, 1);
    }
    
    // 自减 1,并返回自增之前的值    
    public final int getAndDecrement() {
    
    
        return unsafe.getAndAddInt(this, valueOffset, -1);
    }
}

From the source code, we can see that the thread-safe operation methods are all implemented using unsafe methods at the bottom. The above unsafe methods are not implemented in Java and are all thread-safe.

2.AtomicReference

AtomicInteger is to increase and decrease the value of the int type. What if the Atomic object is a custom class? Java also provides an atomic operation class for custom objects called AtomicReference. The operable object of the AtomicReference class is generic, so it supports custom classes. The bottom layer has no self-increment method. The operation method can be passed as a function parameter. The source code is as follows:

// 对 x 执行 accumulatorFunction 操作
// accumulatorFunction 是个函数,可以自定义想做的事情
// 返回老值
public final V getAndAccumulate(V x,BinaryOperator<V> accumulatorFunction) {
    
    
    // prev 是老值,next 是新值
    V prev, next;
    // 自旋 + CAS 保证一定可以替换老值
    do {
    
    
        prev = get();
        // 执行自定义操作
        next = accumulatorFunction.apply(prev, x);
    } while (!compareAndSet(prev, next));
    return prev;
}

Guess you like

Origin blog.csdn.net/weixin_43935927/article/details/108718208