0

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:

    1. Why does weakCompareAndSet() exist in AtomicInteger? Why would I ever choose to use it while compareAndSet() 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.

    1. Surprisingly, there is a raw set() method in AtomicInteger, which is not even labelled atomic! What is it doing in a class like AtomicInteger?!
softwarelover
  • 1,009
  • 1
  • 10
  • 22

0 Answers0