compareAndSet on processors that does not support CAS operation

别说谁变了你拦得住时间么 提交于 2021-02-10 03:28:57

问题


Today I was asked the next question on an interview: "What is going on with compareAndSet method from AtomicLong in case you call it on a machine with a processor that does not support CAS operation".

Could you please help me with this question and provide some links to a comprehensive description if possible?


回答1:


From Java Concurrency in Practice 15.2.3 CAS support in the JVM :

On platforms supporting CAS, the runtime inlines them into the appropriate machine instruction(s); in the worst case, if a CAS-like instruction is not available the JVM uses a spin lock.




回答2:


Take a look at the AtomicLong class source. We can find this:

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

It means it will work in eatiher case. Depending on the implementation JVM may try to acquire lock and if it could not try again (polling).

Judging by the comment, JVM uses 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);
}


来源:https://stackoverflow.com/questions/46817970/compareandset-on-processors-that-does-not-support-cas-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!