2017-10-18 85 views
3

今天我在接受采访时被问到下一个问题:“如果您在具有不支持CAS操作的处理器的计算机上调用它,AtomicLong中的compareAndSet方法会发生什么? ”。不支持CAS操作的处理器上的compareAndSet

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

回答

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(); 

这意味着它会在更大的情况下工作。根据实现,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); 
} 
+0

首先非常感谢您的回复。但是我对支持CAS的处理器和不支持处理器的行为的确切区别感兴趣。看起来,如果处理器不支持CAS,则会为compareAndSet方法执行一些其他类型的同步。我需要更多的细节。 – Illia

+0

不幸的是,我不知道有关确切的区别,除了定期轮询由JVM锁定一些互斥体:)。它没有被指定,并且可能从JVM到JVM有所不同。在非CAS处理器工作原理上,C11方法'std :: atomic :: compare_and_exchange_strong'可能会有所帮助。 –

5

Java Concurrency in Practice15.2.3 CAS支持在JVM

在支持CAS平台,运行时内联它们到适当的机器指令(一个或多个);在最坏的情况下,如果类似CAS的指令不可用,则JVM使用旋转锁定,即 。