当前位置:网站首页>Synchronized underlying principle, volatile keyword analysis
Synchronized underlying principle, volatile keyword analysis
2022-07-07 08:53:00 【Please Sit Down】
synchronized lock
synchronized Lock usage
// synchronized The underlying principle of lock
public class SynchronizedTest03 {
// Modified static method ( Synchronization method )
// Code block 0( Locked is the current class )
public synchronized static void access0(){
try {
TimeUnit.*MINUTES*.sleep(1);
System.*out*.println(Thread.currentThread().getName()+" is running");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Modify non static methods ( Synchronization method )
// Code block 1( What is locked is the caller of the current object )
public synchronized void access1(){
try {
TimeUnit.MINUTES.sleep(1);
System.out.println(Thread.currentThread().getName()+" is running");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Modify non static methods ( Synchronization code block )
// Code block 2( Locked objects )this Refers to the current object
public void access2(){
synchronized(this){
try {
synchronized (this){
TimeUnit.*MINUTES*.sleep(1);
}
System.*out*.println(Thread.currentThread().getName()+" is running");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// Code block 3( What's locked is CLASS class )( Synchronization code block )
public void access3(){
synchronized(SynchronizedTest03.class){
//ClassLoader class --> “ Pile up ” Area generates a Class object : All objects
// Yes Class All objects of the object share this lock
try {
TimeUnit.MINUTES.sleep(1);
System.out.println(Thread.currentThread().getName()+" is running");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
SynchronizedTest03 demo = new SynchronizedTest03();
for (int i = 0; i < 5; i++) {
new Thread(demo::access2).start();
}
}
}
Classification of locks :
1、 Object lock
synchronized(this|object) {} Modify non static methods
stay Java in , Every object will have a monitor object , This object is actually *** yes Java The lock of the object ***, Usually it will be *** be called “ Built in lock ” or “ Object lock ”***. Class can have more than one object , So each object has its own object lock , Mutual interference .
***monitor object ( The monitor )***:
A、 When a thread owns the object , First look at monitor Is the counter of 0, If it is 0 There are no threads yet , At this time, the thread occupies the object , And for this object monitor+1; If not for 0, Indicates that this thread has been occupied by other threads , This thread waits . When the thread releases possession ,monitor-1;
B、 The same thread can lock the same object many times , Just lock it once monitor+1, Reentrancy .
2、 Kind of lock
synchronized( class .class) {} Modified static method
stay Java in , There is also a lock for each class , Can be called “ Kind of lock ”, Class locks are actually implemented through object locks , namely *** Class Class Object lock ***. There is only one for each class Class object , So each class has only one class lock .
synchronized Principle analysis
1、 Thread stack analysis (Jconsole、Jstack pid)
We start the above program 5 Threads , Each thread sleeps 1 minute , We use Jconsole Software to view threads .
We can see that there is 5 Threads , A thread is waiting , other 4 All threads are blocked .
Use Jstack pid Look at the thread :
2、JVM Command analysis
Decompile the current class :javap -v SynchronizedTest03
Find what we wrote access0、access1、access2、access3 Method : among access0、access1 The same principle ( The way to lock ),access2、access3 The same principle ( Lock code block ).
A、 Lock code block ( use monitor Lock and unlock )
【 problem 】 Why are there two monitorexit?
answer : The first is the normal exit , The second is the exception exit .
B、 The way to lock ( Lock with a mark 、ACC_SYNCHRONIZED)
3、 Use synchronized Attention problem
(1) And moniter The associated object cannot be empty
(2)synchronized Scope too large
(3) Different monitor Trying to lock the same way
(4) The intersection of multiple locks leads to deadlock
Java Virtual machines are right synchronized The optimization of the
Lock optimization is added : Biased locking 、 Lightweight lock 、 Heavyweight lock ( Long waiting time )
every last monitor Stored in an instance object , Every object is associated with monitor Association , It is mainly associated with the object header , Association is mainly based on the status of the lock .
No lock state : No locks
Biased locking : When an object is first occupied by a thread , Whether it is biased to lock 1, Lock table 01, Write thread number , When other lines When Cheng visited , Will compete , The competition failure ( Upgrade to lightweight lock )、 Many times, the thread that owns it for the first time gets more times – Competitive success
Lightweight lock : Threads have alternate applications , Mutual exclusion is not very strong ,CAS Failure ,00
Heavyweight lock : Strong mutual exclusion ,10, Long waiting time
spinlocks : When the competition fails , It's not about changing levels right now , It's a couple of empty loops
Lock elimination :JIT Remove unnecessary locks when compiling
volatile keyword
Machine hardware CPU And JMM Model
(1)CPU Cache Model
Multicore CPU Under the circumstances :
(2)CPU Cache consistency
every last CPU To memory cache They don't interfere with each other , It is easy to cause data inconsistency .
every last CPU Steps to modify memory data :
1、 Read data from memory to Cache in
2、 stay Cache Update data in
3、 Refresh the updated results to memory
Solution :
A) The bus is locked ( The granularity is too large )
B)MESI( Cache consistency protocol )
a. Read operations : Not doing anything , hold Cache Read the data in the register
b. Write operations : Send a signal to inform others CPU Changing variables Cache line Set to invalid , Other CPU To access this variable , Can only get... From memory .( A cache is actually a set of lines called cache lines (cache line) Fixed size data block , Its size is based on the size of burst read or burst write cycles , When fetching a cell from memory to cache In the middle of the day , One at a time cacheline Memory area of size to cache in , Then save the corresponding cacheline in , The smallest unit )
(3)Java Memory model
\1) The data in main memory can be accessed by all threads ( Shared data )
\2) Each thread has its own workspace ,( Local memory 、 Private data )
\3) Workspace data : local variable 、 Copy of memory
\4) Threads cannot directly modify data in memory , You can only read the workspace to modify , Refresh to memory after modification
JMM and CPU Memory is directly related :
Volatile Semantic analysis of keywords
volatile effect : Let other threads immediately perceive the modification of a thread with more than one variable
(1) Guaranteed visibility
Changes to shared variables , Other threads can immediately sense
Atomicity is not guaranteed , Such as : read 、 Write 、(i++)
(2) To ensure order
Reorder ( Compile phase 、 Instruction optimization phase ), The code order of the input program is not the order of actual execution , Reordering has no effect on a single thread , Have an impact on Multithreading .
Happens-before Medium volatile The rules :
about volatile Decorated variable :
(1)volatile The previous code can't be adjusted behind him
(2)volatile The subsequent code cannot be adjusted to the front of it (as if seria)
(3) The position does not change
(3)volatile Principle and implementation mechanism of ( lock 、 Lightweight )
HSDIS --> Decompile --> assembly
Volatile Usage scenarios of
(1) Status flag ( Switch mode )
public class ShutDownDemo extends Thread{
private volatile boolean started=false;
@Override
public void run() {
while(started){
// Code logic
}
}
public void shutdown(){
started=false;
}
}
(2) Double check lock (DCL:double-checked-locking)
public class SingletonDemo {
// volatile The function of is to make the data object thread in memory visible
// Main memory is invisible to threads , add to volatile After keyword , Main memory is visible to threads
// Use volatile Skip the working memory directly after copying a copy , Perform main memory operation to determine whether it is empty
// If not volatile, May cause instruction rearrangement , Cause null pointer exception
private volatile static SingletonDemo singleton;
private SingletonDemo(){
System.out.println(" Created a singleton object !");
}
// double check
public static SingletonDemo getInstance(){
// Must be a unique object
if(singleton == null){
synchronized (SingletonDemo.class){
if(singleton == null){
singleton = new SingletonDemo();
}
}
}
return singleton;
}
}
analysis : No addition volatile The influence of keywords
Modify the code :
private Socket socket;
private static SingletonDemo singleton;
private SingletonDemo(){
socket = new Socket();
singleton = new SingletonDemo();
socket.toString();
}
At initialization time , according to JVM Optimize , May cause instruction rearrangement , Lead to socket.toString() Execute preferentially without being initialized , It will cause null pointer exception , So it must be added volatile keyword , such singleton = new SingletonDemo(); The previous code will not be changed, and the execution order will not appear null pointers .
(3) You need to take advantage of sequencing
volatile And synchronized The difference between
(1) Differences in use :volatile Only variables can be decorated ,synchronized Only methods and statement blocks can be modified
(2) Assurance of atomicity :synchronized You can guarantee atomicity ,volatile Atomicity is not guaranteed
(3) Guarantee of visibility : It's all about visibility , But the implementation principle is different
volatile Add... To the variable lock,synchronized Use monitorEnter and monitorexit
(4) Guarantee of order
volatile Can ensure order ,synchronized It can ensure order , But the price ( heavyweight ) Concurrency degenerates to serial
(5) other
3) You need to take advantage of sequencing
volatile And synchronized The difference between
(1) Differences in use :volatile Only variables can be decorated ,synchronized Only methods and statement blocks can be modified
(2) Assurance of atomicity :synchronized You can guarantee atomicity ,volatile Atomicity is not guaranteed
(3) Guarantee of visibility : It's all about visibility , But the implementation principle is different
volatile Add... To the variable lock,synchronized Use monitorEnter and monitorexit
(4) Guarantee of order
volatile Can ensure order ,synchronized It can ensure order , But the price ( heavyweight ) Concurrency degenerates to serial
(5) other
synchronized Cause obstruction 、volatile No blocking
边栏推荐
- QT charts use (rewrite qchartview to realize some custom functions)
- The longest ascending subsequence model acwing 1017 Strange thief Kidd's glider
- 数据分析方法论与前人经验总结2【笔记干货】
- A bug using module project in idea
- 阿里p8推荐,测试覆盖率工具—Jacoco,实用性极佳
- Greenplum 6.x build_ Environment configuration
- Test pits - what test points should be paid attention to when adding fields to existing interfaces (or database tables)?
- About using CDN based on Kangle and EP panel
- Mock. JS usage details
- Compilation and linking of programs
猜你喜欢
随机推荐
数字三角形模型 AcWing 275. 传纸条
LeetCode 715. Range module
年薪50w阿里P8亲自下场,教你如何从测试进阶
模拟卷Leetcode【普通】1567. 乘积为正数的最长子数组长度
Rapid integration of authentication services - harmonyos platform
PPT模板、素材下载网站(纯干货,建议收藏)
Explain Huawei's application market in detail, and gradually reduce 32-bit package applications and strategies in 2022
数据分片介绍
测试踩坑 - 当已有接口(或数据库表中)新增字段时,都需要注意哪些测试点?
C language for calculating the product of two matrices
Novice entry SCM must understand those things
对API接口或H5接口做签名认证
Shell script for changing the current folder and the file date under the folder
说一个软件创业项目,有谁愿意投资的吗?
【MySQL】数据库进阶之触发器内容详解
Greenplum6.x重新初始化
How to realize sliding operation component in fast application
Count sort (diagram)
Isomorphic C language
The longest ascending subsequence model acwing 1017 Strange thief Kidd's glider