当前位置:网站首页>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
边栏推荐
- RuntimeError: Calculated padded input size per channel: (1 x 1). Kernel size: (5 x 5). Kernel size c
- Greenplum 6.x common statements
- 如何统计项目代码行数
- [wechat applet: cache operation]
- Greenplum 6.x monitoring software setup
- Pointer advanced, string function
- Compilation and linking of programs
- 求有符号数的原码、反码和补码【C语言】
- 模拟卷Leetcode【普通】1706. 球会落何处
- Vagrant failed to mount directory mount: unknown filesystem type 'vboxsf'
猜你喜欢
Explain Huawei's application market in detail, and gradually reduce 32-bit package applications and strategies in 2022
MySQL主从延迟的解决方案
南京商品房买卖启用电子合同,君子签助力房屋交易在线网签备案
Interpolation lookup (two methods)
NCS Chengdu Xindian interview experience
Greenplum 6.x build_ Environment configuration
How to realize sliding operation component in fast application
数字三角形模型 AcWing 1027. 方格取数
为不同类型设备构建应用的三大更新 | 2022 I/O 重点回顾
xray的简单使用
随机推荐
MAC OSX php dyld: Library not loaded: /usr/local/xxxx. dylib
Mock.js用法详解
Mountaineering team (DFS)
Greenplum 6.x common statements
Explain Huawei's application market in detail, and gradually reduce 32-bit package applications and strategies in 2022
NCS Chengdu Xindian interview experience
路由信息协议——RIP
Upload an e-office V9 arbitrary file [vulnerability recurrence practice]
Gson转换实体类为json时报declares multiple JSON fields named
Goldbach conjecture C language
selenium自动化集成,八年测试经验软测工程师,一篇文章带你学懂
【MySQL】数据库进阶之触发器内容详解
xray的简单使用
[Yugong series] February 2022 U3D full stack class 007 - production and setting skybox resources
Required String parameter ‘XXX‘ is not present
leetcode134. gas station
OpenGL三维图形绘制
opencv 将16位图像数据转为8位、8转16
Digital triangle model acwing 275 Pass a note
调用华为游戏多媒体服务的创建引擎接口返回错误码1002,错误信息:the params is error