Following on from hello, what is your understanding of Synchronized? (ii), this article will talk about bias locking that implements lock escalation with synchronized.

Iv. Lock upgrade

Prior to Java 1.6, synchronized was the standard heavyweight lock. When multiple threads competed for a shared resource, the uncontested thread would remain blocked, resulting in a significant performance overhead, as well as a significant resource consumption for both locking and releasing locks. In order to reduce performance overhead and improve efficiency, four lock states are subdivided according to different locking scenarios, including no lock, biased lock, lightweight lock, and heavyweight lock. The lock state will be upgraded from low to high according to the intensity of contention for resources.

4.1 biased locking

Many times, locks are acquired multiple times by the same thread, and no threads compete for locks. In this case, bias locking is good, so when is bias locking? In Chapter 3, we show that Markword memory layouts vary widely among different lock states of synchronized.

4.1.1 Biased lock acquisition

When a thread accesses a code block or method modified by the synchronized keyword, it stores the ID of the current thread in Markword. When another thread tries to enter the synchronized block, it compares whether the current thread ID stored in Markword is the ID of the thread attempting to enter the synchronized block through CAS. If it is equal, There is no need to acquire the lock again, and the synchronized code block can be executed directly. If not, the current bias lock is in favor of another thread, and you need to undo the bias lock, and then upgrade the lock to lightweight.

4.1.2 Biased lock revocation

Undo biased locking does not actually undo the lock, leaving it in an unlocked state. For biased lock undo, there are two cases, both for the thread originally holding it and for the lock itself.

  • If the original holding thread just finished executing, exiting the synchronized block, then theMarkwordThe saved thread ID is set to null.
  • If the original holding thread is still executing in the synchronized block, the biased lock is upgraded to a lightweight lock and the original thread continues executing.

The figure below shows the flow of threads T1 and T2 competing to lock resources under a block of code decorated with synchronized.

The next chapter deals with lightweight and heavyweight locks. Hello, what is your understanding of Synchronized? (4)


Hey, man, don’t panic! Leave a like and comment. Welcome to the column face interview don’t panic | Java concurrent programming, a raise don’t have to worry about the interview. Also welcome to pay attention to me, must do a long more good man.