Cas
This instruction full name compare and swap is the comparison substitution instruction, which is newly added to the modern processor instruction.
Guideline: Based on optimistic locking mechanism. Compares the value of a variable in memory value and the current value of the variable (old value). If it is equal, the variable is considered unchanged and the new value is used instead of the old value, otherwise the substitution fails.
Unsafe
In a multithreaded environment of Java programs, if a variable is accessed by multiple threads, to ensure thread safety, in addition to volatile, lock, final, and static methods, you can use Java-provided Sun.misc.Unsafe class
Two features of this class:
Platform-related (Java language Platform-independent), written in C language. The Compareandswap method is provided for the Java class.
Not in the Java API, we can only use some of the official Java-provided classes, such as atomic, random, etc.
Now that we have no way to use unsafe directly, let's look at how this class is used in the JDK.
The application of CAs in Java class