Synchronized bias lock, lightweight lock, heavyweight lock

Synchronized bias lock, lightweight lock, heavyweight lock

(1) Biased lock: In the object header of the lock object, record the thread id that currently acquires the lock. If the thread wants to acquire the lock next time, it can be acquired directly.
(2) Lightweight lock: It is upgraded from a biased lock. When a thread acquires a lock, the lock is a biased lock. If there is a second thread to compete for the lock at this time, the biased lock will be upgraded to Lightweight locks, the reason why they are called lightweight locks, are to separate them from heavyweight locks. Lightweight locks are implemented by spinning and will not block threads.
(3) If the lock has not been obtained after spinning for many times, it will be upgraded to a heavyweight lock, which will cause the thread to block.
(4) Spin lock: A spin lock means that the thread will not block the thread during the process of acquiring the lock, so it does not matter to evoke the thread. The two steps of blocking and waking up need to be implemented by the operating system, which is time-consuming. The spin lock is a thread that obtains the expected mark through CAS. If it is not obtained, it will continue to obtain it in a loop. If it is obtained, it means that the lock has been obtained. This process thread is always running, and relatively speaking, it does not use too many operating system resources. , relatively lightweight.

The difference between Synchronized and ReentrantLock

(1) synchronized is a keyword, and ReentrantLock is a class.
(2) synchronized will automatically lock and release the lock, RenntrantLock requires the programmer to manually release and lock.
(3) The bottom layer of synchronized is a lock at the JVM level, and ReentrantLock is a lock at the API level.
(4) synchronized is an unfair lock, ReentrantLock can choose a fair lock or an unfair lock.
(5) synchronized locks the object, and the lock information is stored in the object header. ReentrantLock represents the state of the lock through the int type state identifier in the code.
(6) The bottom layer of synchronized has a state of lock upgrade.

Guess you like

Origin blog.csdn.net/weixin_49131718/article/details/131794999