About the concept of synchronized lock upgrade, many blogs speak very clearly, here I will tell you my personal understanding, convenient for you to understand, if there is a description of the incorrect place, please correct, very grateful.

Synchronized is a built-in Java synchronization mechanism, which is also referred to as Intrinsic Locking. Synchronization provides mutually exclusive semantics and visibility. When one thread has acquired the lock, other threads attempting to acquire the lock must wait or block.

What’s important about synchronized?

Prior to JDK1.6, synchronized added synchronization by locking a block of code directly when a thread accessed the resource being locked. All other threads will be blocked in the blocking queue. The end is awakened one by one. The operation to block and wake up the thread needs the help of the operating system, which needs to switch from user mode to kernel mode. Operating system this operation is very slow, heavy is heavy here.

What has changed about synchronized since JDK1.6?

After JDK1.6, the entire synchronized operation will gradually upgrade the lock based on concurrency.

Deflection lock

If an object is synchronized, it is always accessed by the same thread. The thread ID is stored in the object header of the object, in a section of the object header called MarkWord. Indicates that the object is biased toward this thread. When this thread comes in again, it sees its own thread ID in the object header. This is biased locking.

Lightweight lock

In the case of a skew lock, if another thread also wants to access the synchronized object. The thread will attempt to write its thread ID into the MarkWord via CAS, and if it succeeds, it will acquire the lock.

Heavyweight lock

When the CAS write fails, it spins several times. When the CAS write exceeds a certain number, it eventually upgrades to a heavyweight lock. In this case, it behaves like synchronized in the early JDK, calling the operating system mutex. The current thread is blocked.

reference

How to implement synchronized low-level? What are the upgrades and downgrades of locks? : link.