当前位置:网站首页>Deflection lock / light lock / heavy lock lock is healthier. How to complete locking and unlocking
Deflection lock / light lock / heavy lock lock is healthier. How to complete locking and unlocking
2022-06-30 20:44:00 【Java Architect in Penghu】
Lightweight locks upgrade to heavyweight locks
- When only one thread grabs JVM Upper deflection lock
- When a thread appears, it is a lightweight lock . Lightweight lock through CAS To lock . If it fails, spin occurs
- When the spin is a certain degree or , Another thread lock appears , It will switch to heavyweight lock .
class Heavy{ } public class HeavyLock
{
public static void main(String[] args) throws InterruptedException
{
Heavy heavy = new Heavy();
final Thread t1 = new Thread(new Runnable()
{
@SneakyThrows
@Override
public void run()
{
synchronized (heavy)
{
System.out.println("t1:"+ClassLayout.parseInstance(heavy).toPrintable());
}
TimeUnit.SECONDS.sleep(1000000);
}
});
final Thread t2 = new Thread(new Runnable()
{
@SneakyThrows
@Override
public void run()
{
synchronized (heavy)
{
System.out.println("t2"+ClassLayout.parseInstance(heavy).toPrintable());
}
TimeUnit.SECONDS.sleep(1000000);
}
});
final Thread t3 = new Thread(new Runnable()
{
@SneakyThrows
@Override
public void run()
{
synchronized (heavy)
{
System.out.println("t3"+ClassLayout.parseInstance(heavy).toPrintable());
}
TimeUnit.SECONDS.sleep(1000000);
}
});
t1.start();
TimeUnit.SECONDS.sleep(2);
t2.start();
t3.start();
TimeUnit.SECONDS.sleep(5);
System.out.println(ClassLayout.parseInstance(heavy).toPrintable());
}
}
- We can find out , When two threads compete for lightweight locks, they will switch to heavyweight locks .

All heavyweight locks at the same time , I find that other information is fixed , This is the same as our memory layout , Here is the lock pointer , The corresponding is C++ in ObjectMonitor Object pointer . There is a queue inside the heavyweight pointer, which is used to suspend the threads that are not robbed . So it won't change here . Here, pay attention to and threads id Distinguish
- After the heavyweight lock is used up, it will be released into an unlocked state .

Lock operation
- Above, we introduced the bias lock , Lightweight lock , Definition of heavyweight lock and scene switching . Here we will summarize three lock usage scenarios
- Bias locked in JVM Under the condition of opening bias , The default is bias lock
- When another thread locks the object again , Whether there is competition or not, it is a lightweight lock . It's just that when there is competition, it will pass CAS preemption ,CAS If it fails for a certain number of times, the heavyweight lock will be upgraded . The process of switching from biased lock to lightweight lock is to undo the biased lock on the lightweight lock first
- When there are two or more competition, it will switch to heavyweight lock . Before switching, there will be a thread waiting through spin . The default is 10 Time . This is not fixed , Because of the existence of adaptive spin lock
- Except for the relationship between locks , We also need to master the principle of each lock , The whole process of locking and unlocking
- Biased locking locked First, we check whether the status bit is 101. If you are looking at the current markword Stored threadId Is it the current thread . If it is the current thread, it can execute the current code block If it's not the current thread , Through CAS Write to the current thread ; If the write is successful, it indicates that the bias lock is locked successfully , Continue executing the current code block If CAS Write failure , It indicates that there is resource preemption . Upgrade deflection lock to lightweight lock .

### Unlock - In the above code list , I also mentioned that the bias lock will not be released automatically . Because when we haven't locked it yet, the default is to bias the lock . Only when there is competition to upgrade the lightweight lock will the partial lock be revoked .- Therefore, the unlocking of the bias lock is not operated . Here we mainly talk about the logic of revoking biased locks when upgrading lightweight locks

## Lightweight lock ### locked - The lightweight lock locking process requires the help of a `Lock Record` ; It is a memory address stored in the thread stack frame .
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-Mc7pHsa9-1656577825850)(https://upload-images.jianshu.io/upload_images/28037261-93f03f9e95b44e93.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]
- Because the deflection lock does not need to be released , His reentrant lock just doesn't do anything . But in lightweight locks, it involves releasing the lock . So how does lightweight lock embody reentrant ?;- In the figure above, if it is unlocked or biased, the lock will be opened in the process stack LockRecord To store markword My address is `Displaced MardWord`- But in the conditional branch that is already biased to lock , I don't embody the concept of reentrant . In this branch line, it is actually detected that markword It refers to the current stack frame JVM Will still open up a `Lock Record`, It won't write back to markword in .`LockRecord` Will not store the original markword The content of . At this time `LockRecord` Itself is the function of a counter . When you release the reentrant lock, you just delete `LockRecord` Instead of operating markword.- Why? JVM How about this design ? Because this avoids the overhead of each lightweight lock ### Unlock - For lightweight locks , The basis of its performance improvement is “ For most locks , There will be no competition throughout the life cycle ”, If you break this rule, you'll have to pay for mutual exclusion , There's an extra CAS operation , So in the case of multithreading competition , Lightweight locks are slower than heavyweight locks ;

summary
- synchronized As a design that has been criticized , stay JDK1.6 Then it was really revised , Don't look at him like he was before . After all, the introduction of biased locks and lightweight locks has improved performance a lot .
- The bias lock is performed by default , Save scheduling time
- Lightweight lock through CAS Finish waiting , Save tune thread suspended , Wake up, etc
- Heavyweight serializes threads , The concurrency between threads is guaranteed
- The three state locks gradually adapt us to different degrees of concurrency requirements

primary
边栏推荐
- B_QuRT_User_Guide(32)
- B_QuRT_User_Guide(35)
- 第81场双周赛
- Peking University ACM problems 1000:a+b problem
- RP原型资源分享-购物类App
- Lumiprobe protein quantitation - qudye Protein Quantitation Kit
- Lambda expression principle analysis and learning (June 23, 2022)
- B_QuRT_User_Guide(31)
- 1. Introduction to generating countermeasures network
- Go 语言标识符、包名规范
猜你喜欢

RP原型资源分享-购物类App

哈夫曼树(一)基本概念与C语言实现

MySQL:SQL概述及数据库系统介绍 | 黑马程序员

Lumiprobe protein quantitation - qudye Protein Quantitation Kit

B_QuRT_User_Guide(32)

On inline function

Lumiprobe nucleic acid quantitative qudye dsDNA br detection kit

obsidian配合hugo的使用,让markdown本地编辑软件与在线化无缝衔接

Lumiprobe 聚乙二醇化和 PEG 接头丨碘-PEG3-酸研究

uniapp怎么上传二进制图片
随机推荐
Informatics Olympiad 1362: family problems
Analysis of breakpoint continuation and download principle
Lvalue reference and lvalue reference
On inline function
QT qstringlist usage
Failed to configure a DataSource: ‘url‘ attribute is not specified and no embedded datasource could
Jerry's long press reset [chapter]
Lumiprobe细胞生物学丨DiA,亲脂性示踪剂说明书
Comparison between QT and other GUI Libraries
Big God explains open source buff gain strategy live broadcast
Lambda expression principle analysis and learning (June 23, 2022)
BioVendor sRAGE Elisa试剂盒测试原理和注意事项
Go language identifier and package name specification
C file pointer
B_QuRT_User_Guide(31)
谈谈内联函数
亚马逊在阿拉伯联合酋长国限制LGBTQ相关的搜索和产品销售
No "history of blood and tears" in home office | community essay solicitation
RP原型资源分享-购物类App
DEX文件解析 - method_ids解析