不支持CAS操作的处理器上的compareAndSet

时间:2017-10-18 19:39:46

标签: java multithreading compare-and-swap

今天有人在接受采访时被问到下一个问题:“如果你在一台不支持CAS操作的处理器的机器上调用它,那么来自AtomicLong的compareAndSet方法是怎么回事。”

请您帮我解决这个问题,如果可能的话,请提供一些全面描述的链接?

2 个答案:

答案 0 :(得分:5)

来自Java Concurrency in Practice 15.2.3 JVM中的CAS支持

  

在支持CAS的平台上,运行时将它们内联到适当的机器指令中;在最坏的情况下,   如果类似CAS的指令不可用,则JVM使用自旋锁。

答案 1 :(得分:4)

查看AtomicLong类来源。我们可以找到这个:

/**
 * Records whether the underlying JVM supports lockless
 * compareAndSet for longs. While the intrinsic compareAndSetLong
 * method works in either case, some constructions should be
 * handled at Java level to avoid locking user-visible locks.
 */
static final boolean VM_SUPPORTS_LONG_CAS = VMSupportsCS8();

这意味着它将在eatiher案例中起作用。根据实现,JVM可能会尝试获取锁定,如果无法再次尝试(轮询)。

根据评论判断,JVM使用std::atomic::compare_and_exchange_strong

/**
 * ...
 * <p>This operation has memory semantics of a {@code volatile} read
 * and write.  Corresponds to C11 atomic_compare_exchange_strong.
 * ...
 */
@ForceInline
public final boolean compareAndSwapInt(Object o, long offset,
                                       int expected,
                                       int x) {
    return theInternalUnsafe.compareAndSetInt(o, offset, expected, x);
}