Why do we need so many locks? Because different locks occupy different resources, everything is designed to use less resources and program execution faster.
First question. Biased lock: Through previous research, the author of Hotspot found that in most cases there is not only no multi-thread competition for locks, but also always acquired multiple times by the same thread. Biased locks were introduced in order to make it cheaper for threads to acquire locks. Suitable for scenarios where one thread accesses a synchronized code block.
Lightweight lock: Used in scenarios where competition is not very intense or synchronized code blocks execute quickly. It will not block but spin. (After spinning several times, I still haven’t obtained the lock and upgraded it to a heavyweight lock)
The second problem is that if the lightweight lock has not obtained the lock after spinning several times (spin can be understood as a loop), it will expand regardless of the number of threads.
The above is my personal understanding, please refer to this article by Infoq.
Why do we need so many locks? Because different locks occupy different resources, everything is designed to use less resources and program execution faster.
First question.
Biased lock: Through previous research, the author of Hotspot found that in most cases there is not only no multi-thread competition for locks, but also always acquired multiple times by the same thread. Biased locks were introduced in order to make it cheaper for threads to acquire locks. Suitable for scenarios where one thread accesses a synchronized code block.
Lightweight lock: Used in scenarios where competition is not very intense or synchronized code blocks execute quickly. It will not block but spin. (After spinning several times, I still haven’t obtained the lock and upgraded it to a heavyweight lock)
The second problem is that if the lightweight lock has not obtained the lock after spinning several times (spin can be understood as a loop), it will expand regardless of the number of threads.
The above is my personal understanding, please refer to this article by Infoq.