Overview of the underlying implementation of Java synchronized locks

Bias lock

By default, the JVM enables biased locking. The first bit of the lock flag in the object header is used to mark whether the biased lock is available.
Lock mark 01 indicates a biased lock.

Bias lock release

The thread that obtains the biased lock has the thread id written in the object header, and will not actively release the lock:

  • There is no other thread contention, the object header is always the tid that acquired the lock.
  • Thread tid2 competes, and tid1 still exists in objhead at this time. The JVM first safely suspends tid1 to determine whether tid1 is still in the synchronized block. If so, it needs to upgrade the lock; if not, it means that tid1 does not need a lock, and the tid field in objhead is set to zero - release the lock. Threads can again contend for biased locks.

This is the meaning of biased lock. It is biased towards the thread that has acquired the lock. By default, the lock is not released. Only when the competition occurs, can the lock be released. If the lock is still required at this time, the competition fails, and it can be determined that the thread competition is more frequent. Therefore, An upgrade lock is required.

CASE

CAS is the key operation for acquiring locks, probably a method such as boolean CAS (objhead.tid, markword, selftid_markword), where markword is the markword in the unlocked state, mainly to test whether the objhead has no lock (tid) when the lock mark is 01. ==0), if so, set your own tid to indicate locking.
The essence of a lock is a state quantity, and the key point of competing for a lock is that checking the state and setting the state are done atomically.

Lightweight lock

Spin 5000 times

The thread occupying the lock uses cas to release the lock after the synchronization code ends. When there is competition, the lock mark at this time has been modified by the competitor to heavyweight lock 10. The cas operation fails, and the locked thread continues to release according to the new lock mark. Locks, at this time, multiple threads compete according to heavyweight locks.

heavyweight lock

Using OS's Mutex Lock

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325214429&siteId=291194637