AtomicLong的incrementAndGet()

来源:互联网 发布:mastercam新手编程 编辑:程序博客网 时间:2024/04/30 20:25

调用顺序为:incrementAndGet--->compareAndSet--->compareAndSwapLong


最后这个函数是一个native函数,这个函数中,第一个形参传入的实参为this(调用者),第三和第四个参数中传入实参是incrementAndGet()中读取的两个变量current和next=current+1。因此cas底层的做法是:如果this的值为current,那就把this的值改为current+1。


源代码如下:

/**
     * Atomically increments by one the current value.
     *
     * @return the updated value
     */
    public final long incrementAndGet() {
        for (;;) {
            long current = get();
            long next = current + 1;
            if (compareAndSet(current, next))
                return next;
        }
    }



/**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     *
     * @param expect the expected value
     * @param update the new value
     * @return true if successful. False return indicates that
     * the actual value was not equal to the expected value.
     */
    public final boolean compareAndSet(long expect, long update) {
        return unsafe.compareAndSwapLong(this, valueOffset, expect, update);
    }



 /**
     * Atomically update Java variable to <tt>x</tt> if it is currently
     * holding <tt>expected</tt>.
     * @return <tt>true</tt> if successful
     */
    public final native boolean compareAndSwapLong(Object o, long offset,
                                                   long expected,
                                                   long x);
0 0
原创粉丝点击