当前位置:网站首页>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
边栏推荐
- 19.04 分配器
- 北京大学ACM Problems 1006:Biorhythms
- Openfire solves the problem of Chinese garbled code after using MySQL database
- Huffman Tree (1) Basic Concept and C - language Implementation
- Game 81 biweekly
- Basic components of STL
- Peking University ACM problems 1005:i think I need a houseboat
- Peking University ACM problems 1003:hangover
- 【微服务~Nacos】Nacos之配置中心
- obsidian配合hugo的使用,让markdown本地编辑软件与在线化无缝衔接
猜你喜欢
浅谈代码语言的魅力
Study on lumiprobe modified triphosphate biotin-11-utp
Lumiprobe nucleic acid quantitative qudye dsDNA br detection kit
Jenkins can't pull the latest jar package
Lambda expression principle analysis and learning (June 23, 2022)
Evolution of screen display technology
Maya House Modeling
RP原型资源分享-购物类App
杰理之触摸按键识别流程【篇】
Lumiprobe核酸定量丨QuDye dsDNA BR 检测试剂盒
随机推荐
SQL必需掌握的100个重要知识点:创建和操纵表
树基本概念
19.04 分配器
What are database OLAP and OLTP? Same and different? Applicable scenarios
Jerry's long press reset [chapter]
第81场双周赛
DEX文件解析 - method_ids解析
A complete collection of vulnerability scanning tools. Mom doesn't have to worry that I won't find any more vulnerabilities
Openfire solves the problem of Chinese garbled code after using MySQL database
Failed to configure a DataSource: ‘url‘ attribute is not specified and no embedded datasource could
How can I get the stock account opening discount link? In addition, is it safe to open a mobile account?
Implementation principle of PostgreSQL heap table storage engine
Document contains & conditional competition
1045 error occurred in MySQL login. Modification method [easy to understand]
B_QuRT_User_Guide(34)
Lumiprobe 改性三磷酸盐丨生物素-11-UTP研究
Lumiprobe染料酰肼丨BDP FL 酰肼方案
在线教育项目用户登录和注册
Lumiprobe protein quantitation - qudye Protein Quantitation Kit
PHP require/include 区别