Why are two AtomicIntegers never equal?

前端 未结 9 2139
日久生厌
日久生厌 2020-12-01 18:02

I stumbled across the source of AtomicInteger and realized that

new AtomicInteger(0).equals(new AtomicInteger(0))

evaluates to

9条回答
  •  粉色の甜心
    2020-12-01 18:32

    I would argue that because the point of an AtomicInteger is that operations can be done atomically, it would be be hard to ensure that the two values are compared atomically, and because AtomicIntegers are generally counters, you'd get some odd behaviour.

    So without ensuring that the equals method is synchronised you wouldn't be sure that the value of the atomic integer hasn't changed by the time equals returns. However, as the whole point of an atomic integer is not to use synchronisation, you'd end up with little benefit.

提交回复
热议问题