Synchronized underlying JVM instructions are
The load memory barrier monitorenter Acquire barrier / * * / release a code block barrier monitorexit store memory barrier -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - monitorenter: If monitor's count=0, the thread enters Monitor and then sets count=1. The thread is the owner of Monitor. If the thread already owns the monitor and just re-enters, count is incremented by 1; If another thread has occupied monitor, it will block until monitor's count=0, and then try again to acquire monitor's ownership. Monitorexit: When the instruction executes, count of monitor decreases by 1. If count = 0, the thread exits the monitor and is no longer the owner of the monitor. Other threads blocked by the monitor can try to obtain the monitor's proprietary load memory barrier by performing the refresh processor cache operation and flushing variables changed by other processors from other processors to the cache or main memory to ensure that the latest data store memory barrier is available: Allow the thread to flush the variable changed in the synchronized block into the cache or main memory through the Flush processor cache. Acquire barrier: Forbid reordering of read operations with subsequent reads and writes. Release Barrier: Forbid reordering of write operations with subsequent writesCopy the code
EntrySet: If a thread already holds an object lock, it can only enter the EntrySet and be BLOCKED if another thread wants to acquire the lock.
WaitSet: If a thread calls wait(), it releases the lock on the object, enters WaitSet, and is in a WAITING state
When a thread is competing for synchronized lock, it will enter EntryList first and try to change count through CAS. If count=0 is successfully changed to count=1, the lock is obtained. When a thread acquires the lock, the Owner area stores information about the thread that acquired the lock.
Lock optimization: to be continued