当前位置:网站首页>Advanced multi threading: the underlying principle of synchronized, the process of lock optimization and lock upgrade
Advanced multi threading: the underlying principle of synchronized, the process of lock optimization and lock upgrade
2022-07-28 05:35:00 【A salted fish..】
List of articles
Tips : The following is the main body of this article ,Java The series of learning will be continuously updated
One 、synchronized Underlying principle
Java Object composition
We all know that the object is placed on Heap memory Medium , The object can be roughly divided into three parts , They are object heads , Instance variables and padding bytes

MarkWord
synchronized Whether it's decorating methods or code blocks , Synchronization is achieved by holding the lock of the decorated object , that synchronized Where is the lock object ?
The answer is There is an object header of the lock object Mark Word, and Mark Word Two messages are stored in : Is the lock biased 、 Lock flag position 
principle :
stay Java in , Objects are in heap memory , And there is an object header in the object , Object header has MarkWord Information used to store locks .
MarkWord There are two signs in : Is the lock biased 、 Lock flag position ( unlocked / Lightweight lock / Heavyweight lock / GC Mark )
The type and state of the lock are in the object header Mark Word There are records in , Applying for a lock 、 Lock upgrade, etc JVM You need to read the object Mark Word data .synchronized To lock an object is to modify the value of these two lock flags in the object header .
When one Java After the object is locked , Will point to a Monitor object ( The monitor ), The current thread will also be released after execution monitor( lock ) And reset the value of the variable , So that other threads can get in monitor( lock ). monitor The object exists in every Java In the object header of the object ( The point of the stored pointer ),synchronized Lock is obtained by this way , That's why Java Any object in can be used as the reason for the lock , It's also notify/ notifyAll/ wait Such methods exist in Object The reason in
Two 、JVM Yes synchronized The optimization of the
Lock elimination
compiler +JVM Determine whether the lock needs to be removed : In the case of a single thread , Or multithreading without competing locks , Will eliminate the lock to improve efficiency .
StringBuffer sb = new StringBuffer();
sb.append("a");
sb.append("b");
sb.append("c");
String str = sb.toString();
Lock coarsening
If there are many times of locking and unlocking in a logic , compiler + JVM The lock will be coarsened automatically .
public class Demo {
// Fine grain
public void test1() {
Object o = new Object();
for(int i = 0; i < 100; i ++){
synchronized(o){
System.out.println(" Perform tasks ");
}
}
}
// Proper coarsening
public void test2() {
Object o = new Object();
synchronized(o){
for(int i = 0; i < 100; i ++){
System.out.println(" Perform tasks ");
}
}
}
}
Lock escalation
synchronized There are four states of lock , unlocked , Biased locking , Lightweight lock , Heavyweight lock , These States will escalate with the state of competition , Locks can be upgraded but not degraded , But biased lock state can be reset to unlocked state
unlocked < ——> Biased locking ——> Lightweight lock ——> Heavyweight lock
3、 ... and 、 Lock escalation process
Biased locking
When there is no lock competition , Often, a thread acquires the same lock multiple times , If you have to compete for locks every time, it will increase the unnecessary cost , To reduce the cost of acquiring locks , The biased lock introduced .
The core idea :
If a thread
Lock for the first time, Then the lock goes into biased mode , here Mark Word The structure of is also changed to biased lock structure , When the thread requests the lock again , There's no need to do any more synchronization , That is, the process of obtaining the lock , This saves a lot of lock application operations , So that's the performance of the provider .
therefore , When there is no lock competition , Biased lock has a good optimization effect , After all, it is very likely that the same thread applies for the same lock many times in a row . But for the lock competition is more intense , The deflection lock fails . After the biased lock fails , It doesn't immediately inflate into a heavyweight lock , Instead, upgrade to a lightweight lock .
Lightweight lock
Lightweight locks consider the of competing lock objects
Not many threads, And the thread holds the lockIt's not longScenario .
Because blocking threads requires expensive and time-consuming implementation CPU Switch from user mode toKernel modeHandoff , If the lock is released soon after the block , Then the price is a little more than worth , So at this time, we don't block this thread at all , Let it spin and wait for the lock to release .
The thread is spinning , Will constantly request locks . If multiple requests fail , It will expand to heavyweight lock .
Heavyweight lock
The locking mechanism is heavily dependent on OS Provides mutex lock , Lock application failed , Have to give up CPU, Go into blocking mode
· A large number of kernel mode user mode switching
· It's easy to trigger thread scheduling
The heavyweight lock passes through the monitor inside the object (monitor) Realization , among monitor The essence of is dependent on the underlying operating system Mutex Lock Realization , The switching between threads of the operating system requires the switching from user state to kernel state , Switching costs are very high .
Advantages and disadvantages
| The lock state | advantage | shortcoming | Applicable scenario |
|---|---|---|---|
| Biased locking | Locking and unlocking do not require additional consumption , Nanosecond time difference from asynchronous method | If there are many competing threads , Then there will be additional consumption of lock revocation | There is basically no thread contention lock synchronization scenario |
| Lightweight lock | Competing threads don't block , Use spin , Improve the response speed of the program | If - You can't get the lock , Self application for a long time will cause CPU Consume | Suitable for a small number of threads competing for lock objects , And the thread does not hold the lock for a long time , The scene of pursuing response speed |
| Heavyweight lock | Thread contention does not apply CPU The spin , Will not lead to CPU Idle consumption CPU resources | Thread blocking , Long response time | Many threads compete for locks , And the lock is held for a long time , The scenario of pursuing throughput |
summary :
Tips : Here is a summary of the article :
The above is today's learning content , This article is about Java Multithreaded learning , I understand synchronized The underlying principle of ,JVM Yes syn Optimization made , And the specific process of lock upgrade . After that, the learning content will be continuously updated !!!
边栏推荐
猜你喜欢

自定义Json返回数据

Scanf function of input and output function in C language

正则表达式
![Classes and objects [medium]](/img/0a/955d00d63f06e7e15e946599628edf.png)
Classes and objects [medium]
![[computer level 3 information security] overview of information security assurance](/img/f0/a72e61fda58ea93ca4e9db7274f6e3.png)
[computer level 3 information security] overview of information security assurance

Framework step by step easy-to-use process

How to compare long and integer and why to report errors

regular expression

FusionGAN代码学习(一)

MySQL practice 45 lectures
随机推荐
IDEA配置 service(Run Dashboard) 服务,多模块同时启动
New arrow function in ES6
oracle查看锁表语句、解锁方法
sql 查询list时两次的数据不一致,自动加上了limit
Mabtis(一)框架的基本使用
Personal summary of restful interface use
低照度图像数据集
7. < tag string and API trade-offs> supplement: Sword finger offer 05. replace spaces
ResNet结构对比
Operation and use of collection framework
【idea插件神器】教你如何使用IDEA一键set实体类中所有属性
New methods and features of ES6 built-in objects
C language: addition and deletion of linked list in structure
C language: some self realization of string functions
SimpleDateFormat线程不安全和DateTimeFormatter线程安全
Scanf function of input and output function in C language
pytorch使用hook获得特征图
Share several methods of managing flag bits in C program
Bean的作用域、执行流程、生命周期
Problems encountered when the registry service Eureka switches to nocas