当前位置:网站首页>Lock upgrade: no lock, bias lock, lightweight lock, heavyweight lock
Lock upgrade: no lock, bias lock, lightweight lock, heavyweight lock
2022-07-26 00:54:00 【Know what you know】
Lock escalation
JDK 1.6 Before ,synchronized It's also a heavyweight lock , It's an inefficient lock . But in JDK 1.6 after ,JVM In order to improve the efficiency of lock acquisition and release synchronized optimized , Biased lock and lightweight lock are introduced , Since then, there have been four lock states : unlocked 、 Biased locking 、 Lightweight lock 、 Heavyweight lock . And the four states will gradually upgrade with the competition , And it's an irreversible process , I.e. not releasable , The order of the four locks from low to high is : unlocked 、 Biased locking , Lightweight lock , Heavyweight lock .

unlocked
No lock does not lock resources , All threads can access and modify the same resource , But at the same time, only one thread can modify successfully .
The characteristic of no lock is that the modification is carried out in the loop , Threads are constantly trying to modify shared resources . If there is no conflict, modify successfully and exit , Otherwise, it's going to keep trying . If multiple threads modify the same value , There must be a thread that can be modified successfully , Other threads that fail to modify will try again and again until the modification succeeds .CAS Principle and application is the realization of no lock . No lock can't replace a lock completely , But the performance of unlocked in some cases is very high .
Biased locking
Biased lock means that a piece of synchronous code is always accessed by a thread , Then the thread will automatically acquire the lock , Reduce the cost of lock acquisition .
in the majority of cases , Locks are always acquired multiple times by the same thread , There is no multi-threaded contention , So there's a bias lock . The goal is to improve performance when only one thread executes a synchronized block of code .
When a thread accesses a synchronized block of code and acquires a lock , Will be in Mark Word Lock in thread biased storage ID. It is no longer passed when a thread enters and exits a synchronization block CAS Operate to lock and unlock , It's detection Mark Word Whether there are biased locks pointing to the current thread stored in . Biased locks are introduced to minimize unnecessary lightweight lock execution paths without multithreading competition , Because the acquisition and release of lightweight locks depend on many times CAS Atomic directive , And biased locks only need to be replaced ThreadID Rely on it once CAS Atomic instructions can be .
Biased locks only encounter when other threads try to compete for biased locks , The thread holding the biased lock will release the lock , Threads do not actively release biased locks . Partial lock revocation , Need to wait for global security ( No bytecode is executing at this point in time ), It first pauses the thread that owns the biased lock , Determine whether the lock object is in the locked state . Return to unlocked after undoing biased lock ( Sign bit is “01”) Or lightweight locks ( Sign bit is “00”) The state of .
Bias locked in JDK 6 And beyond JVM It is enabled by default . Can pass JVM Valuepoint close bias lock :-XX:-UseBiasedLocking=false, After closing, the program will enter the lightweight lock state by default .
Lightweight lock
When a lock is biased toward a lock , Accessed by another thread , Biased locks will be upgraded to lightweight locks , Other threads try to acquire the lock by spinning , It won't block , To improve performance .
When the code enters the synchronized block , If the lock state of the synchronization object is unlocked ( The lock flag bit is “01” state , Whether it is biased lock or not is “0”), The virtual machine starts by creating a record called a lock in the current thread's stack frame (Lock Record) Space , Used to store the current lock object Mark Word A copy of the , Then copy the... In the object header Mark Word Copy to lock record .
After copying successfully , The virtual machine will be used CAS The operation attempt will object Mark Word Update to point Lock Record The pointer to , And will Lock Record Inside owner Pointer to the object Mark Word.
If the update action succeeds , The thread then owns the lock on the object , And object Mark Word The lock flag bit of is set to “00”, Indicates that the object is in a lightweight locked state .
If the update operation of the lightweight lock fails , The virtual machine first checks the object Mark Word Whether to point to the current thread's stack frame , If so, the current thread already has the lock of this object , Then you can go straight to the synchronized block and continue , Otherwise, multiple threads compete for locks .
If there is currently only one waiting thread , Then the thread waits through spin . But when the spin exceeds a certain number of times , Or a thread holding a lock , One is spinning , There was a third visit , Upgrade lightweight lock to heavyweight lock .
Heavyweight lock
When upgrading to a heavyweight lock , The status value of the lock flag becomes “10”, here Mark Word Stored in is a pointer to a heavyweight lock , At this time, the threads waiting for the lock will enter the blocking state .
Heavyweight locks obviously , There is a limit to this busy wait ( There's a counter that records the number of spins , Loop is allowed by default 10 Time , It can be changed by virtual machine parameters ). If the lock competition is serious , A thread that has reached the maximum number of spins , Will upgrade lightweight lock to heavyweight lock ( Is still CAS Modify lock flag bit , But do not modify the thread holding the lock ID). When a subsequent thread attempts to acquire a lock , It is found that the lock occupied is a heavyweight lock , Then hang yourself up ( Instead of waiting ), Waiting for the future to be awakened .
The overall lock status upgrade process is as follows :

Sum up , Bias lock by contrast Mark Word Solve the lock problem , Avoid execution CAS operation . And lightweight locks are made by using CAS Operation and spin to solve the lock problem , Avoid thread blocking and wake-up and affect performance . A heavyweight lock blocks all threads except the thread that owns the lock .
边栏推荐
- jupyter更改主界面并且导入数据集
- 参数解析器HandlerMethodArgumentResolver分析与实战
- C # from entry to mastery (III)
- Redis (VIII) - redis enterprises' actual coupons spike
- typing‘ has no attribute ‘_SpecialForm‘
- Compile openfoam solver with cmake
- [oops framework] network module websocket
- Leetcode notes 121. the best time to buy and sell stocks
- 【oops-framework】随机数生成管理
- Open download! Alibaba Devops Practice Manual
猜你喜欢
随机推荐
【RTOS训练营】作业讲解、队列和环形缓冲区、队列——传输数据、队列——同步任务和晚课提问
Amin's confession
[RTOS training camp] program framework, preview, after-school homework and evening class questions
Analysis and practice of parameter parser handlermethodargumentresolver
【RTOS训练营】上节回顾、空闲任务、定时器任务、执行顺序、调度策略和晚课提问
Travel + strategy accelerated landing, jietu new product matrix exposure
【RTOS训练营】程序框架、预习、课后作业和晚课提问
Tell you the meaning of unit testing from another angle
Microwave oven rectifier diode cl01-12
The bumpy road of referencing jar package json-path.jar in jmeter/idea
985高校副教授晒年薪,公积金顶普通人月薪,网友:不愧是在上海
Hcip day 11
HCIP 第十一天
hcia综合实验
从另一个角度告诉你单元测试的意义
【RTOS训练营】继续程序框架、tick中断补充、预习、课后作业和晚课提问
AI knows everything: build and deploy sign language recognition system from 0
Spine_附件皮肤
Upload local file trial version using SAP ui5 fileuploader control
Cnosdb Nirvana Rebirth: abandon go and fully embrace rust









