当前位置:网站首页>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 !!!
边栏推荐
- ssm项目快速搭建项目配置文件
- Operation and use of collection framework
- List < long >, list < integer > convert each other
- Performance test classification
- MySQL uses list as a parameter to query
- (黑马)MYSQL初级-高级笔记(博主懒狗)
- First acquaintance with C language (1)
- openjudge:病人排队
- There is no crossover in the time period within 24 hours
- Oracle创建表、删除表、修改表(添加字段、修改字段、删除字段)语句总结
猜你喜欢

MySQL basic query

Personal summary of restful interface use

regular expression

MySQL date and time function, varchar and date are mutually converted

使用navicat或plsql导出csv格式,超过15位数字后面变成000(E+19)的问题

JUC笔记

VMware Workstation 与 Device/Credential Guard 不兼容。禁用 Device/Credential Guard

How to compare long and integer and why to report errors

集合框架的操作使用

ByteBuffer. Position throws exception illegalargumentexception
随机推荐
IDEA使用dev-tool实现热部署
11. < tag dynamic programming and subsequence, subarray> lt.115. Different subsequences + Lt. 583. Deletion of two strings DBC
JVM篇 笔记4:内存模型
[slam] lvi-sam analysis - Overview
SSLError
解决Oracle使用in语句不能超过1000问题
What are the methods of array objects in Es5 and what are the new methods in ES6
Scope, execution process and life cycle of bean
URL 形式
GET与POST区别
7. < tag string and API trade-offs> supplement: Sword finger offer 05. replace spaces
【单例模式】懒汉模式的线程安全问题
Multi module packaging: package: XXX does not exist
pytorch 计算模型的GFlops和total params的方法
MySQL adds sequence number to query results
多线程进阶:volatile的作用以及实现原理
mybaties foreach多选查询,index循环,取消and/or标签
测试开发---自动化测试中的UI测试
mysql 为查询结果增加序号
使用navicat或plsql导出csv格式,超过15位数字后面变成000(E+19)的问题