A CAS (compare and set) operator is built into the instruction set of almost every processor today (in some form or another). It is atomic. And it is use to implement the basic mutex (synchronization) funntionality.
This is probably a standard homework question for a computer architecture class, so I'll stop here. How do you think it works? Given the capability to conditionally set or swap a value, based on its current value, how would you implement synchronization?
BTW, as a side note, the
Java Virtual Machine actually doesn't have a CAS in its instruction set. Instead, it implements the higher level monitor in and out (synchronization) directly. I guess this is so that it can do synchronization with one bytecode instruction.
Unfortunately, without a CAS, you have to rely on synchronization for everything, making it impossible to code optimistically. This is why they added the Atomic Variables in Java 5 -- this is basically a set of variables that implements a form of CAS (obviously using JNI under the covers to get to the CAS operator).
Henry