UNSAFE.compareAndSwapObject具体是做什么的?

9
我阅读JDK ConcurrentLinkedQueue时,发现UNSAFE.compareAndSwapObject非常奇怪。(class CLQ是从ConcurrentLinkedQueue复制过来的,以便于调试...) 当我将第一个项目提供给ConcurrentLinkedQueue时。

代码:ConcurrentLinkedQueue.class offer()

public boolean offer(E e) {
    checkNotNull(e);
    final Node<E> newNode = new Node<E>(e);

    for (Node<E> t = tail, p = t;;) {
        Node<E> q = p.next;
        if (q == null) {
            // p is last node
            if (p.casNext(null, newNode)) {
                // Successful CAS is the linearization point
                // for e to become an element of this queue,
                // and for newNode to become "live".
                if (p != t) // hop two nodes at a time
                    casTail(t, newNode);  // Failure is OK.
                return true;
            }
            // Lost CAS race to another thread; re-read next
        }
        else if (p == q)
            // We have fallen off list.  If tail is unchanged, it
            // will also be off-list, in which case we need to
            // jump to head, from which all live nodes are always
            // reachable.  Else the new tail is a better bet.
            p = (t != (t = tail)) ? t : head;
        else
            // Check for tail updates after two hops.
            p = (p != t && t != (t = tail)) ? t : q;
    }
}

1
嗯,你已经涉及到了不安全的领域。然而,我的猜想是在CPU级别上涉及到了cmpxchg(比较并交换)指令。不过我也不能确定。 - fge
1
“cas” 意味着“比较并设置”,它会像名称所示的那样,将旧值与指定的第一个参数(这里是 null)进行比较,并在比较成功时设置为指定的第二个参数(这里是 newNode)。特别之处在于它是以原子方式执行的。有一个公共 API 为应用程序提供相同的功能 - Holger
在许多情况下,compareAndSet调用“native”api。@fge,你的猜测是正确的。 - chain ro
1个回答

0

它可能类似于以下伪代码,但是是用所谓的本地代码(C/C++)编写的,通常比Java快得多:

boolean compareAndSwapObject(Object obj, long fieldId, Object expectedValue, Object newValue) {
    synchronized (globalExchangeLock) {
        if (obj.fieldArray.get(fieldId) == expectedValue) {
            obj.fieldArray.set(fieldId, newValue);
            return true;
        }
    }
    return false;
}

private static final Object globalExchangeLock = new Object();

然而,传递fieldId有点复杂,可能应该像下面的Java代码一样进行缓存(这次不是伪代码):

public class MyClass {
    int myField;

    // ...

    private static final sun.misc.Unsafe U = UnsafeAcc.unsafe;
    private static final long MY_FIELD_ID;

    static {
        try {
            MY_FIELD_ID = U.objectFieldOffset(
                MyClass.class.getDeclaredField("myField")
            );
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }
}

我的Android项目使用:

/*
 * Written by Stefan Zobel and released to the
 * public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */
package java8.util.concurrent;

import java.lang.reflect.Field;

import sun.misc.Unsafe;

final class UnsafeAcc {

    static final Unsafe unsafe;

    static {
        try {
            Field field = null;
            try {
                field = Unsafe.class.getDeclaredField("theUnsafe");
            } catch (NoSuchFieldException ignored) {
                // For older Androids.
                field = Unsafe.class.getDeclaredField("THE_ONE");
            }
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    private UnsafeAcc() {
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接