当前位置:网站首页>Advanced multithreading (6) -- locking mechanism
Advanced multithreading (6) -- locking mechanism
2022-04-22 22:46:00 【Classmate Xiaoqu】
Basic concepts of multithreading : Getting started with multithreading ( One )
Multi thread basic implementation : Getting started with multithreading ( Two )
Multithreading Management : Multithreading Foundation ( 3、 ... and )
State transitions between threads : Multithreading Foundation ( Four )
Communication between threads : Multi thread advanced ( 5、 ... and )
This article , Let's talk about java Multithreaded " lock ".
First of all, make it clear :Java Multithreaded locks are object-based ,Java Every... In ⼀ Both objects can be used as ⼀ A lock
Multi thread advanced ( 6、 ... and ) Locking mechanism
1、synchronized
synchronized Chinese means synchronous , Also known as ” Synchronization lock “. Role is Make sure that at the same time , The modified code block or method will only have one thread executing , In order to achieve the effect of ensuring concurrent security .
1.1 Scope
We usually make ⽤ synchronized Keywords to ⼀ A piece of code or ⼀ individual ⽅ Can't lock . It usually has the following three forms :
// Keyword in instance ⽅ Legally , Lock is the current instance
public synchronized void instanceLock() {
// code
}
// Keywords in static ⽅ Legally , Lock is current Class object
public static synchronized void classLock() {
// code
}
// Keyword on code block , The lock is in parentheses ⾥⾯ The object of
public void blockLock() {
Object o = new Object();
synchronized (o) {
// code
}
}
1.2 Several locks
An object actually has four lock states , They have low to high , In turn, is :
- No lock state
- Biased lock state
- Lightweight lock state
- Heavyweight lock state
Several locks , As the competition escalates , Lock upgrades can easily occur , But the conditions under which demotion occurs are very harsh .
The following describes several locks and lock upgrades between them :
1.3 Biased locking
⼤ Most of the time Locks don't just have multithreaded competition ,⽽ And always by the same ⼀ The thread gets more than once , So it leads to ⼊ The deflection lock .
Biased locking biases the first thread to access the lock , If in the next run , There are no other threads competing for the lock , Then the thread holding the lock will never trigger synchronization , It improves the running performance of the program .
1.3.1 principle
principle : When a thread first enters a synchronized code block , Lock records in the object header and stack frame ⾥ Store lock biased threads ID. The next time the thread enters the synchronized code block again , Will go to the object head mark word Check the tag in the , Whether there is a thread with its own thread ID.
If it is , Indicates that the thread has For the lock , Go to sync code block , No longer need to spend CAS Operation to lock and unlock .
If not , Represents another thread competing for biased locks , Now CAS Will try to replace mark word The thread of ID Thread for new thread ID.
- success , Indicates the old thread ID Does not exist. , Replacement successful , At this time, I still prefer to lock .
- Failure , Indicates the old thread ID There is still a , At this time, it will be upgraded to lightweight lock , Will compete for locks in the way of lightweight locks .
1.3.2 Upgrade process
When the bias lock is upgraded to a lightweight lock , Will pause the thread using the lock , Reset the deflection lock identification , The general process is as follows :
- The system will first find a time point when there is no bytecode in execution ,, Then stop the thread that owns the lock ;
- Traverse the thread stack , Repair or modify
mark word, Make it unlocked ; - Wake up the stopped thread , Make it a lightweight lock ;
therefore , If we should ⽤ Program ⾥ All locks are usually in a competitive state , Then the bias lock will be ⼀ A burden , We can turn it off by default .
-XX:UseBiasedLocking=false.
1.4 Lightweight lock
Multiple threads acquire the same lock at different times , There is no lock competition .
1.4.1 principle
If a thread finds a lightweight lock when it obtains a lock , You'll lock it mark word Copied to the dispace mark word Inside . Then try to use CAS Lock it mark word Replace with a pointer to the lock record .
- success , Current thread gets lock ;
- Failure , Table name
mark wordHas been replaced with lock records of other threads , Next, I'll try The spin To get the lock , If you can't get , Upgrade to heavyweight lock .
A diagram illustrates the process of locking and releasing the lock :

1.5 Heavyweight lock
Heavyweight locks depend on the mutex of the operating system (mutex) Realized ,⽽ State transitions between threads in the operating system are required ⽐ a ⻓ Time for , therefore The efficiency of heavyweight lock is very low .
When multiple threads request an object lock at the same time , Object locks are set ⼏ States ⽤ To distinguish the thread of the request :
- Contention List: All threads that request locks will be locked ⾸ Put into the competition queue first
- Entry List:Contention List Which of them are eligible to be candidates ⼈ Thread moved to Entry List
- Wait Set: Those tunes ⽤wait⽅ Method blocked threads are placed in Wait Set
- OnDeck: At most at any time ⼀ Threads are competing for locks , This thread is called OnDeck
- Owner: The thread that obtains the lock is called Owner
- !Owner: The thread that releases the lock
When the thread releases the lock , From Contention List or EntryList in choose ⼀ Thread wakeup , The selected thread is called Heir presumptive Assumed inheritance ⼈, Assumed inheritance ⼈ When you wake up, you try to get a lock , but synchronized yes ⾮ Fair , So assume inheritance ⼈ No ⼀ You can get the lock . This is because for heavyweight locks , Xian Chengxian ⾃ Spin attempt to obtain lock , Doing so ⽬ To reduce obsession ⾏ Overhead of operating system synchronization . If ⾃ If the rotation fails, advance again ⼊ Waiting in line . This is for threads that are already in the waiting queue , Slightly unfair , also ⼀ An unfair land ⽅ yes ⾃ The thread may be preempted Ready Thread lock .
1.6 Comparison of various locks

1.7 Summarize the upgrade process of lock
- Every time ⼀ When a thread is ready to acquire a shared resource : The first ⼀ Step , Check MarkWord⾥⾯ Did you put it ⾃⼰ Of ThreadId , If it is , Indicates that the current thread is in “ Biased locking ” .
- The first ⼆ Step , If MarkWord No ⾃⼰ Of ThreadId, Lock escalation , Now ,⽤CAS To hold ⾏ Switch , The new thread is based on MarkWord⾥⾯ The existing ThreadId, Thread paused before notification , Before the thread take Markword The content of the is set to null .
- The third step , Both threads lock the object's HashCode Copied to the ⾃⼰ New ⽤ The record for the storage lock is empty between , And then it started to go through CAS operation , Lock the object MarKword The content of is modified to ⾃⼰ New record The address of the space ⽅ Competitive MarkWord.
- Step four , In the third step, successfully execute ⾏CAS Access to resources , If you fail, go to ⼊⾃ Spin .
- Step five ,⾃ The spinning thread is ⾃ During spinning , Successful access to resources ( That is, the thread execution of the previously obtained resource ⾏ End And released shared resources ), Then the whole state is still in the state of lightweight lock , If ⾃ Spin failed .
- Step six , Into the ⼊ State of heavyweight lock , This is the time ,⾃ Screw the thread into ⾏ Blocking , The thread executes before waiting ⾏ Complete and wake up ⾃⼰.
版权声明
本文为[Classmate Xiaoqu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204222207175361.html
边栏推荐
- Graph and numerical representation of knowledge map of knowledge representation
- scanpy find resolution
- 396. 旋转函数 / 剑指 Offer II 013. 二维子矩阵的和
- GBase 8s V8.8 SQL 指南:教程-6.2.1(2)
- NLP direction -- interview and written test question set (7): pre training model Bert
- 【零散知识点总结5】
- Reinforcement learning (practice): feedback, AC
- How should enterprises make disaster recovery plans for Cloud Computing?
- vickers威格士比例阀的特点
- 【MMUB】基于Hidden Markov model的手机用户行为建模——Hidden Markov model
猜你喜欢

2.57-编写程序show_short, show_long和show_double,它们分别打印类型为short, long和double的C语言对象的字节表示。请试着在几种机器上运行。

Centos7安装mysql

Overview of working principle and main characteristics of ATOS proportional valve

GBase 8s V8. 8 SQL Guide: Tutorial - 6.2.1 (2)

High end beer is losing young people
![[wechat applet development (cloud wallpaper applet tutorial)]](/img/71/d1ec9b0e7af47427c1e19b9b949bfa.png)
[wechat applet development (cloud wallpaper applet tutorial)]

【洛谷】P1162 填涂颜色(bfs)

初学单片机点亮第一个外设--LED灯

scanpy find resolution
![[summary of scattered knowledge points 5]](/img/a6/6700f00b01bc59fc0366d64071ac41.png)
[summary of scattered knowledge points 5]
随机推荐
O0 O1 O2 O3优化原理
Overview of working principle and main characteristics of ATOS proportional valve
GBase 8s V8.8 SQL 指南:教程-6.2.2(1)
How to use opcua protocol on appinventor?
中缀转后缀表达式(逆波兰式) 转 前缀表达式(波兰式)
GBase 8s V8.8 SQL 指南:教程-6.2.2(3)
Youqilin 22.04 lts version is officially released | ukui 3.1 opens a new experience!
On the law of enterprise informatization
vickers威格士比例阀的特点
SecureCRT v7. 0 failed to connect to sshd service. Solution
How to judge how many levels of insurance the enterprise should do? What is the significance of waiting insurance?
Pangolin安装报错:make: *** 没有规则可制作目标“pypangolin_pip_install”。 停止。
ACL2022 | 利用中文语言层级异质图强化预训练语言模型
4 / 21 Kunming supplementary questions + mathematics
Analysis of real questions and answers of software designers in the morning in the second half of 2021
【零散知识点总结5】
repeat_map mp.find() + mp.erase()
hawe哈威液压泵站的液压冲击分析
In the future, platofarm's ecological pass can be logged into bitmart and other four major global platforms
NLP direction -- interview and written test question set (7): pre training model Bert