2017-10-18 86 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使用旋轉鎖定,即 。