当前位置:网站首页>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
边栏推荐
- Why choose cloud native database
- opencv 将16位图像数据转为8位、8转16
- 详解华为应用市场2022年逐步减少32位包体上架应用和策略
- Speaking of a software entrepreneurship project, is there anyone willing to invest?
- 9c09730c0eea36d495c3ff6efe3708d8
- let const
- Gson转换实体类为json时报declares multiple JSON fields named
- Nanjing commercial housing sales enabled electronic contracts, and Junzi sign assisted in the online signing and filing of housing transactions
- 测试踩坑 - 当已有接口(或数据库表中)新增字段时,都需要注意哪些测试点?
- Category of IP address
猜你喜欢

平台化,强链补链的一个支点

調用華為遊戲多媒體服務的創建引擎接口返回錯誤碼1002,錯誤信息:the params is error

Three series of BOM elements

xray的简单使用

2022-07-06 Unity核心9——3D动画

Why choose cloud native database

The longest ascending subsequence model acwing 1017 Strange thief Kidd's glider

MySQL主从延迟的解决方案

How to integrate app linking services in harmonyos applications

Image segmentation in opencv
随机推荐
Analysis of abnormal channel number information before and after AGC re signature service
C language for calculating the product of two matrices
Explain Huawei's application market in detail, and gradually reduce 32-bit package applications and strategies in 2022
模拟卷Leetcode【普通】1567. 乘积为正数的最长子数组长度
测试踩坑 - 当已有接口(或数据库表中)新增字段时,都需要注意哪些测试点?
Implement custom memory allocator
Uniapp wechat applet monitoring network
如何在图片的目标中添加目标的mask
如何在快应用中实现滑动操作组件
Problems encountered in the use of go micro
Greenplum6.x搭建_环境配置
Skills that testers must know: Selenium's three waiting ways are interpreted clearly
Greenplum 6.x build_ install
数字三角形模型 AcWing 275. 传纸条
LeetCode 715. Range module
更改当前文件夹及文件夹下文件日期shell脚本
MySQL主从延迟的解决方案
[Yugong series] February 2022 U3D full stack class 008 - build a galaxy scene
Routing information protocol rip
opencv 将16位图像数据转为8位、8转16