Java 在不支持CAS操作的处理器上比较数据集

Java 在不支持CAS操作的处理器上比较数据集,java,multithreading,compare-and-swap,Java,Multithreading,Compare And Swap,今天,我在一次采访中被问到了下一个问题:“AtomicLong中的compareAndSet方法发生了什么,以防在一台不支持CAS操作的处理器上调用它” 你能帮我回答这个问题吗?如果可能的话,请提供一些链接到全面的描述?看看AtomicLong类源代码。我们可以发现: /** * Records whether the underlying JVM supports lockless * compareAndSet for longs. While the intrinsic compare

今天,我在一次采访中被问到了下一个问题:“AtomicLong中的compareAndSet方法发生了什么,以防在一台不支持CAS操作的处理器上调用它”


你能帮我回答这个问题吗?如果可能的话,请提供一些链接到全面的描述?

看看
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();
这意味着它将在其他情况下起作用。根据实现情况,JVM可能会尝试获取锁,如果无法重试(轮询)

根据评论判断,JVM使用了

/**
* ...
*此操作具有{@code volatile}读取的内存语义
*然后写。对应于C11原子\u比较\u交换\u强。
* ...
*/
@强制内联
公共最终布尔比较器ADSWAPINT(对象o,长偏移,
int预期,
整数x){
返回内部不安全。比较设置(o,偏移量,预期值,x);
}
来自JVM中的15.2.3 CAS支持的

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


首先,非常感谢您的回复。但我感兴趣的是,支持CA的处理器和不支持CA的处理器的行为有一个确切的区别。在不支持CAS的处理器中,似乎还有一些其他类型的同步用于比较数据集方法。我需要更多的细节。不幸的是,我不知道确切的区别,除了JVM定期轮询一些被锁定的互斥锁:)。它没有指定,可能因JVM而异。也许非CAS处理器工作原理上的C11方法
std::atomic::compare\u和\u exchange\u 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);
}