In some scenarios , To get the object lock CAS The way , It's not blocking .
Lightweight lock can improve program synchronization performance “ For most locks , There is no competition in the whole synchronization cycle ”, This is an empirical data .
stay Java Object In the header file , There is one “Mark Word” object , It is the key to implement lightweight locks .
Mark Word The data structure is not fixed , There are different structures according to different states .
For example, in the 32 Bit HotSpot When the object in the virtual machine is not locked ,Mark
Word Of 32bit In space 25bit Used to store the object hash code ,4bit Used to store the generation age of objects ,2bit The lock mark is used to store the lock ,1bit Fixed to 0.
The main states are as follows ：
state Marker bit Store content
Not locked 01 Object hash code , Generation age of subjects
Lightweight locking 00 Pointer to the lock record
Heavyweight locking 10 Pointer to a heavyweight lock
GC sign 11 empty , There is no need to record information
Biased 01 Thread bias ID, Biased timestamp , Generation age of subjects
<> Lightweight lock locking process
（1） When the code enters the synchronization block , If the lock state of the synchronization object is lock free （ Lock flag bit is “01” state ）, The virtual machine will first create a record called lock in the stack frame of the current thread （Lock
Record） Space for , Used to store old Mark Word Copy of , It's officially called Displaced Mark Word.( Lock record will be used when unlocking )
（2） Virtual machines will use CAS The operation attempts to set the Mark Word Flag bit and pointer lock record updated to lightweight lock （Lock Record） Pointer to .
（3） If the update is successful , Then the thread owns the lock of the object .
（4） If the update fails , The virtual machine first checks whether the current thread has a lock on the object , If you already have , Then you can go directly to the synchronization block to continue execution . Otherwise, it means that the lock degree has been preempted by other threads . Once this happens , Then lightweight locks will expand into heavyweight locks .Mark
Word A pointer to a heavyweight lock is stored in , The thread waiting for the lock will also enter the blocking state .
<> Lightweight lock unlock process
（1） adopt CAS Operation attempts to copy the Displaced Mark Word Object to replace the current Mark Word.
（2） If the replacement is successful , The whole synchronization process is complete .
（3） If the replacement fails , Indicates that another thread has tried to acquire the lock , The lock becomes a heavyweight lock , Then release the lock at the same time , Wake up suspended thread .
<> Drawing comprehension
use New Mark Word replace Old Mark Word.
use Displaced Mark Word replace New Mark Word.