Reputation: 997
I am trying to understand at a high level how java's concurrent API built using AbstractQueuedSynchronizer
as a building block. I didn't see any use of synchronized
, wait()
+ notify()
inside this class. Then how it is possible to achieve a thread-safe code?
Although I saw unsafe
CAS operations to achieve some atomicity, but that is not enough to have fully thread safe code.
Upvotes: 3
Views: 242
Reputation: 6884
The Unsafe
class is not as well documented as classes publicly exposed by the JDK, so not all guarantees its methods make are obvious.
However, if you look at the latest source code of AbstractQueuedSynchronizer
, you will see that it now uses VarHandle
whose methods are well documented. For compareAndSet
the documentation says:
Atomically sets the value of a variable to the newValue with the memory semantics of setVolatile(java.lang.Object...) if the variable's current value, referred to as the witness value, == the expectedValue, as accessed with the memory semantics of getVolatile(java.lang.Object...).
This means there will not be race conditions since for two concurrent threads only one thread will update the value, the other will fail. And you get the needed memory visibility guarantees.
Upvotes: 3