当前位置:网站首页>Multithreading and high concurrency (3) -- synchronized principle
Multithreading and high concurrency (3) -- synchronized principle
2022-04-23 05:49:00 【The green flowers of Wang Li's family】
synchronized Refer to the previous article for usage , Multithreading and high concurrency (2)——synchronized Usage details , Atomicity is also discussed in detail 、 Visibility and mutex . This paper mainly summarizes synchronized Principle .
synchronized The synchronization block of is reentrant for the same thread , There will be no problem of locking yourself .
One 、 Decompile
Let's look at the following code first :
// Object lock : form 1( Method lock )
public synchronized void method1() {
System.out.println(" I am an object lock and a method lock ");
try {
System.out.println(" I want to sleep 500ms");
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Object lock : form 2( Code block form )
public void method2() {
synchronized (this) {
try {
System.out.println(" I'm the object lock , I want to sleep 500ms");
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// Kind of lock : form 1 : Lock static method
public static synchronized void method3() {
System.out.println(" I'm a class lock 1");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void method4() {
synchronized (DemoSync.class) {
System.out.println(" I'm a lock type 2");
}
This is summarized in the last article synchronized usage , Method 12 It's the object of the lock , Method 3 The lock is the whole class ( Or this kind of Class object ). Here we use javap -v Command to class Decompilation of files , The results are as follows .
1、method1
2、method2
3、method3
4、method4
Two 、monitorenter and monitorexit
1、monitorenter
The source code explains this :
Each object is associated with a monitor. A monitor is locked if and only if it has an
owner. The thread that executes monitorenter attempts to gain ownership of the
monitor associated with objectref, as follows:
• If the entry count of the monitor associated with objectref is zero, the thread
enters the monitor and sets its entry count to one. The thread is then the owner of
the monitor.
• If the thread already owns the monitor associated with objectref, it reenters the
monitor, incrementing its entry count.
• If another thread already owns the monitor associated with objectref, the thread
blocks until the monitor's entry count is zero, then tries again to gain ownership.
Which translates as :
Each object has a monitor (monitor), Or tube . When monitor It will be locked when occupied , Threads execute monitorenter Attempt to get monitor The ownership of the , The process is as follows :
(1) If monitor The number of entries is 0, Then the thread enters monitor, Then set the number of entries to 1, This thread is monitor Owner .
(2) If the thread already owns the monitor, Just re-enter , entering monitor The number of entries plus 1.
(3) If other threads are already occupied monitor, Then the thread enters the blocking state , until monitor The number of entries is 0, Try again to get monitor The ownership of the .
2、monitorexit
The thread that executes monitorexit must be the owner of the monitor associated with
the instance referenced by objectref.
The thread decrements the entry count of the monitor associated with objectref. If as
a result the value of the entry count is zero, the thread exits the monitor and is no
longer its owner. Other threads that are blocking to enter the monitor are allowed to
attempt to do so.
Which translates as :
perform monitorexit The thread of must be the corresponding thread of the object monitor Owner .
monitorexit Instruction execution ,monitor The number of entries minus 1, If less 1 The last in number is 0, The thread exits monitor, It's not this anymore monitor Owner . Others are monitor Blocked threads can try to get this monitor The ownership of the .
Synchronized The bottom semantic layer is through a monitor To complete , Actually wait/notify And so on monitor object , That's why it can only be called in synchronized blocks or methods wait/notify Other methods , Otherwise it will throw java.lang.IllegalMonitorStateException The cause of the anomaly .
See the first article in our multithreading series , Multithreading and high concurrency (1)—— Basic knowledge of threads ( Realization , Common methods , state ), It says wait() Method must be in a method decorated with synchronous keywords to call . call notify perhaps notifyAll Method does not release the lock , But let him participate in the lock competition .
3、 ... and 、ACC_SYNCHRONIZED
Method 1 and 3 The synchronization of did not pass the instruction monitorenter and monitorexit To complete ( In theory, it can also be realized by these two instructions ), But compared to the normal way , There are more constant pools ACC_SYNCHRONIZED,ACC_STATIC Identifier .JVM It is based on ACC_SYNCHRONIZED To realize the synchronization of methods :
When a method is called , The call instruction will check the method's ACC_SYNCHRONIZED Whether the access flag is set , If set ,
Execution thread will get first monitor, Method body can only be executed after obtaining success , After method execution ( Whether normal or abnormal )
Re release monitor. During method execution , No other thread can get the same monitor object .
If an exception is thrown during the execution of a synchronization method , And can't handle this exception inside the method , Then the pipe held by the synchronization method will be released automatically when the exception is thrown out of the synchronization method .
There is essentially no difference between the two synchronization modes , But method synchronization is an implicit way to achieve , No bytecode required . The execution of the two instructions is JVM By calling the operating system's mutex primitive mutex To achieve , Blocked threads will be suspended 、 Waiting for rescheduling , It can lead to “ User mode and kernel mode ” Switching back and forth between two states , It has a great impact on the performance .
Four 、 summary
about method1234 Come on , In essence, it is the object to compete monitor, Whoever wins will execute .
版权声明
本文为[The green flowers of Wang Li's family]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230540317160.html
边栏推荐
猜你喜欢
Excel sets row and column colors according to cell contents
2 - principes de conception de logiciels
橙单微服务之批量导入
SQL statement simple optimization
Sea Level Anomaly 和 Sea Surface Height Anomaly 的区别
‘EddiesObservations‘ object has no attribute ‘filled‘
实操—Nacos安装与配置
手动删除eureka上已经注册的服务
开发环境 EAS登录 license 许可修改
Establish excel bookkeeping book through setting context menu
随机推荐
Software architecture design - software architecture style
创建二叉树
软件架构设计——软件架构风格
Data mining -- understanding data
The list attribute in the entity is empty or null, and is set to an empty array
MySQL lock mechanism
PyEMD安装及简单使用
Idea plug-in --- playing songs in the background
事实最终变量与最终变量
[machine learning] scikit learn introduction
mysql如何将存储的秒转换为日期
数据处理之Numpy常用函数表格整理
Radar equipment (greedy)
C language - Spoof shutdown applet
Establish excel bookkeeping book through setting context menu
Pytorch deep learning practice_ 11 convolutional neural network
Linear sieve method (prime sieve)
Introduction to data security -- detailed explanation of database audit system
2-軟件設計原則
Strategy for improving the conversion rate of independent stations | recovering abandoned users