Biased lock
The JVM turns on the biased lock by default. The first bit of the lock flag in the object header is used to mark whether a bias lock is available.
The lock marker 01 indicates a bias lock.
Biased lock release
Gets the thread that favors the lock, writes the wire ID in the object header, does not actively release the lock:
- No other threads compete, and the object header is always the TID that gets the lock.
- Thread Tid2 competition, at this time Objhead still save tid1. The JVM first safely pauses the TID1, determines whether the TID1 is still in the sync block, and if so, upgrades the lock, if not, TID1 does not need a lock, the Tid field in Objhead 0-Release the lock. The thread can compete again to bias the lock.
Biased lock is the meaning, biased to the thread has been acquired to the lock, the default is not released, only when the competition occurs, there is the possibility of releasing the lock, if still need to lock, then the competition failure, you can assume that the thread competition is more frequent, therefore, the need to upgrade the lock.
Cas
CAS is a key operation to get locks, presumably a Boolean CAS (Objhead.tid,markword,selftid_markword) method, where Markword is an unlocked markword, mainly a test lock marked 01 o'clock, Objhead is unlocked (tid==0), if it is, set its own Tid, indicating lock.
The essence of a lock is a state quantity, and the key point of a competitive lock is to check the state and set the state to be atomic.
Lightweight lock spin 5,000 times
The thread that occupies the lock, after the synchronization code ends, uses CAS to release the lock, and when there is competition, the lock mark has been modified by the competitor to the heavyweight lock 10,cas operation failed, the lock thread continues to release the lock according to the new lock tag, at which time the multithreading follows the heavyweight lock competition.
Heavyweight lock using the OS mutex lock
Overview of the underlying implementation of Java synchronized locks