java偏向锁,轻量级锁与重量级锁为什么会相互膨胀?
PHP中文网
PHP中文网 2017-04-18 10:29:58
0
1
513

正在看《深入理解java虚拟机》 对于锁膨胀不是很明白。
首先偏向锁,我理解偏向锁和轻量级锁之间区别是在获取锁的过程中,是否有CAS操作。但是为什么偏向锁不能直接替代轻量级锁,什么场景是轻量级锁能够解决但是偏向锁无法解决的呢?

第二个 书上402页上面说“如果有两条以上的线程竞争用同一个锁,轻量级锁就不再有效,要膨胀为重量级锁”,我的理解上不需要大于两个线程,等于两个线程的竞争情况下,也需要膨胀对吗?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(1)
伊谢尔伦

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!