当前位置:网站首页>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
边栏推荐
- filebrowser实现私有网盘
- JVM系列(3)——内存分配与回收策略
- mysql如何将存储的秒转换为日期
- MySQL create Oracle exercise table
- 尚硅谷 p290 多态性练习
- Record a project experience and technologies encountered in the project
- ES6之解构函数
- Golang通过exec模块实现Ping连通性检测案例
- 创建线程的三种方式
- io.lettuce.core.RedisCommandExecutionException: ERR wrong number of arguments for ‘auth‘ command
猜你喜欢

Excel sets row and column colors according to cell contents

opensips(1)——安装opensips详细流程

2 - software design principles

域内用户访问域外samba服务器用户名密码错误

框架解析1.系统架构简介

Package mall system based on SSM

The 8th Blue Bridge Cup 2017 - frog jumping cup

2 - principes de conception de logiciels

JDBC连接数据库

Flutter 新一代图形渲染器 Impeller
随机推荐
ES6之解构函数
Error 2003 (HY000) when Windows connects MySQL: can't connect to MySQL server on 'localhost' (10061)
字符串(String)笔记
图解HashCode存在的意义
【华为机试】考试得分总数(如何处理答错的情况?回溯一次,代表答错一题)
XXL job pit guide XXL RPC remoting error (connect timed out)
MySQL transaction
Range of numbers (dichotomous classic template topic)
Understand the current commonly used encryption technology system (symmetric, asymmetric, information abstract, digital signature, digital certificate, public key system)
Redis经典面试题总结2022
Solid contract DoS attack
io.lettuce.core.RedisCommandExecutionException: ERR wrong number of arguments for ‘auth‘ command
lambda表达式
MySQL的锁机制
第36期《AtCoder Beginner Contest 248 打比赛总结》
JSP语法及JSTL标签
MySQL lock mechanism
Contract lock loophole
数据处理之Numpy常用函数表格整理
深入源码分析Servlet第一个程序