First, the principle of spin
Simply put: the thread tries to acquire a lock does not block the process, instead of using the cycle continues to acquire locks.
Advantages: reducing kernel mode and user mode switching consumption
Disadvantages: non-stop consumption of CPU Spin
Second, the simple spin-lock hands
2.1 use AtomicReference achieve
AtomicReference Atomicity, the underlying implementation CAS operation, can be cited contrast to the common object.
Source Analysis:
As can be seen from the source code, the underlying AtomicReference, which atomic operations are used to complete unsafe.compareAndSwapObject, CAS will support normal operation of the object.
This operation is AtomicInteger atoms, CAS underlayer for comparison are integers, the AtomicReference no more practical.
2.2 handwriting simple spin-lock Source
2.3 Simple test
More spin lock Reference:
https://blog.csdn.net/qq_17856593/article/details/99679255