AtomicInteger 原子类学习记录

1.AtomicInteger提供java关于integer操作的原子性操作

    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;

    /**
     * Creates a new AtomicInteger with the given initial value.
     *
     * @param initialValue the initial value
     */
    public AtomicInteger(int initialValue) {
        value = initialValue;
    }

    /**
     * Creates a new AtomicInteger with initial value {@code 0}.
     */
    public AtomicInteger() {
    }

内部保存了一个Unsafe对象,一个value和通过Unsafe类型获得的value的偏移量。AtomicInteger依托Unsafe对象提供对value的原子性操作,而不是锁。

Unsafe类,简单来讲就是提供硬件级别的原子性操作

AtomicInteger的读是直接返回value,但是写全部依赖Unsafe类的写操作

猜你喜欢

转载自blog.csdn.net/luwei9233/article/details/88557705