What is the difference between: compareAndSet(...) and weakCompareAndSet(...) methods in AtomicInteger as implementation for both looks same but in java doc for weakCompareAndSet(....) it says that "May fail spuriously"
The words "fail spuriously" in the JavaDoc are a link. If you click on it, you go to a more elaborate description:
The atomic classes also support method weakCompareAndSet, which has limited applicability. On some platforms, the weak version may be more efficient than compareAndSet in the normal case, but differs in that any given invocation of the weakCompareAndSet method may return false spuriously (that is, for no apparent reason). A false return means only that the operation may be retried if desired, relying on the guarantee that repeated invocation when the variable holds expectedValue and no other thread is also attempting to set the variable will eventually succeed. (Such spurious failures may for example be due to memory contention effects that are unrelated to whether the expected and current values are equal.) Additionally weakCompareAndSet does not provide ordering guarantees that are usually needed for synchronization control. However, the method may be useful for updating counters and statistics when such updates are unrelated to the other happens-before orderings of a program. When a thread sees an update to an atomic variable caused by a weakCompareAndSet, it does not necessarily see updates to any other variables that occurred before the weakCompareAndSet. This may be acceptable when, for example, updating performance statistics, but rarely otherwise.
Note that the implementation of the JDK is not exactly the same on all platforms. You've probably looked at the source code of Oracle's JDK, where compareAndSet and weakCompareAndSet are apparently exactly the same. Maybe in someone else's implementation it's different. (Oracle is not the only company that implements the JDK; companies such as IBM and HP have their own implementation of the JDK).
... also just because its the same now doesn't mean it will be in future, this has come up before where Java has changed within the remit of the interface but broke code because client apps relied on a specific implementation i.e. program to the interface.
The interface reserves the right to fail spuriously which other JDK's or a newer JDK might want to make available for the reasons listed in the previous post.
"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5