What does “spurious failure” on AtomicInteger weakCompareAndSet mean?

后端 未结 4 1934
不思量自难忘°
不思量自难忘° 2021-02-05 08:43

The Java AtomicInteger class has a method -

boolean weakCompareAndSet(int expect,int update)

Its documnentation says:

Ma

4条回答
  •  遥遥无期
    2021-02-05 09:21

    It means it might return false (and will not set the new value) even if it currently contains the expected value.

    In other words, the method may do nothing and return false for no apparent reason...
    There are CPU architectures where this may have a performance advantage over a strong CompareAndSet().


    A bit more concrete detail on why something like this might happen.

    Some architectures (like newer ARMs) implement CAS operations using a Load Linked (LL)/Store Conditional (SC) set of instructions. The LL instruction loads the value in a memory location and 'remembers' the address somewhere. The SC instruction stores a value into that memory location if the value at the remembered address has not been modified. It's possible for the hardware to believe that the location has been modified even if it apparently hasn't for a number of possible reasons (and the reasons might vary by CPU architecture):

    1. the location may have been written with the same value
    2. the resolution of the addresses watched might not be exactly the one memory location of interest (think cache lines). A write to another location that's 'close-by' may cause the hardware to flag the address in question as 'dirty'
    3. a number of other reasons that may cause the CPU to lose the saved state of the LL instruction - context switches, cache flushes, or page table changes maybe.

提交回复
热议问题