I am aware that compareAndSet()
in AtomicInteger
is a core method that takes a clever approach to atomically update the current value of the integer primitive that AtomicInteger
encapsulates. It does so only after it has ascertained that another thread has not updated it already, and gives up if it detects otherwise.
Also, I know, the methods in AtomicInteger
labelled "atomic" by the Java API documentation internally invoke compareAndSet()
.
Having expressed the indispensability of compareAndSet()
in AtomicInteger
, my questions are:
- Why does
weakCompareAndSet()
exist inAtomicInteger
? Why would I ever choose to use it whilecompareAndSet()
is available for use? According to the Java API,it may fail spuriously and does not provide ordering guarantees, so is only rarely an appropriate alternative to
compareAndSet
.
- Why does
- Surprisingly, there is a raw
set()
method inAtomicInteger
, which is not even labelled atomic! What is it doing in a class likeAtomicInteger
?!
- Surprisingly, there is a raw