当前位置:网站首页>Multithreading tutorial (XXI) double checked locking problem
Multithreading tutorial (XXI) double checked locking problem
2022-06-11 05:29:00 【Have you become a great God today】
Multithreading tutorial ( The 21st )double-checked locking problem
One 、double-checked locking Imperfect examples of
With the famous double-checked locking Single instance mode as an example
public final class Singleton {
private Singleton() {
}
private static Singleton INSTANCE = null;
public static Singleton getInstance() {
if(INSTANCE == null) {
// t2
// The first visit synchronizes , And then the use did not synchronized
synchronized(Singleton.class) {
if (INSTANCE == null) {
// t1
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
The above implementation features are :
Laziness
For the first time to use getInstance() Only use synchronized Lock , There is no need to lock it for subsequent use
There is an implied , But the key point is : first if Used INSTANCE Variable , It's outside the sync block
But in a multithreaded environment , There is something wrong with the code above ,getInstance The bytecode corresponding to the method is :
0: getstatic #2 // Field INSTANCE:Lcn/itcast/n5/Singleton;
3: ifnonnull 37
6: ldc #3 // class cn/itcast/n5/Singleton
8: dup
9: astore_0
10: monitorenter
11: getstatic #2 // Field INSTANCE:Lcn/itcast/n5/Singleton;
14: ifnonnull 27
17: new #3 // class cn/itcast/n5/Singleton
20: dup
21: invokespecial #4 // Method "<init>":()V
24: putstatic #2 // Field INSTANCE:Lcn/itcast/n5/Singleton;
27: aload_0
28: monitorexit
29: goto 37
32: astore_1
33: aload_0
34: monitorexit
35: aload_1
36: athrow
37: getstatic #2 // Field INSTANCE:Lcn/itcast/n5/Singleton;
40: areturn
among
17 Represents the creation object , Stack object references // new Singleton
20 Represents copying an object reference // Refer to the address
21 Means to use an object reference , Call constructor
24 Means to use an object reference , Assign a value to static INSTANCE
Maybe jvm It will be optimized to : Execute first 24, Re execution 21. If two threads t1,t2 Execute according to the following time series :

The key lies in 0: getstatic This line of code is in monitor Out of control , It's like the irregular person in the previous example , You can cross monitor Read
INSTANCE The value of the variable
At this time t1 The constructor has not been fully executed yet , If you need to perform a lot of initialization operations in the constructor , that t2 What you get will be an early
Single case after initialization
Yes INSTANCE Use volatile Can be modified , Command rearrangement can be disabled , But pay attention to JDK 5 The above version of volatile It really works
Two 、double-checked locking The correct use of
private Singleton() {
}
private static volatile Singleton INSTANCE = null;
public static Singleton getInstance() {
// Instance not created , To get inside synchronized Code block
if (INSTANCE == null) {
synchronized (Singleton.class) {
// t2
// There may be other threads that have created instances , So again
if (INSTANCE == null) {
// t1
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
I can't see it in the bytecode volatile The effect of the command
// -------------------------------------> Join in INSTANCE Variable read barrier
0: getstatic #2 // Field INSTANCE:Lcn/itcast/n5/Singleton;
3: ifnonnull 37
6: ldc #3 // class cn/itcast/n5/Singleton
8: dup
9: astore_0
10: monitorenter -----------------------> Guaranteed atomicity 、 visibility
11: getstatic #2 // Field INSTANCE:Lcn/itcast/n5/Singleton;
14: ifnonnull 27
17: new #3 // class cn/itcast/n5/Singleton
20: dup
21: invokespecial #4 // Method "<init>":()V
24: putstatic #2 // Field INSTANCE:Lcn/itcast/n5/Singleton;
// -------------------------------------> Join in INSTANCE Variable write barrier
27: aload_0
28: monitorexit ------------------------> Guaranteed atomicity 、 visibility
29: goto 37
32: astore_1
33: aload_0
34: monitorexit
35: aload_1
36: athrow
37: getstatic #2 // Field INSTANCE:Lcn/itcast/n5/Singleton;
40: areturn
As shown in the notes above , Reading and writing volatile Variable will be added to the memory barrier (Memory Barrier(Memory Fence)), Make sure the following two points :
visibility
- Write barriers (sfence) Ensure... Before the barrier t1 Changes to shared variables , All synchronized to main memory .
- And the reading barrier (lfence) Ensure that after this barrier t2 Reading shared variables , Loading is the latest data in main memory
Orderliness
The write barrier ensures that when instructions are reordered , Don't put the code before the write barrier behind the write barrier
The read barrier ensures that when instructions are reordered , The code after the read barrier is not placed before the read barrier
At the bottom is the use of... When reading and writing variables lock Instruction to multicore CPU Visibility and order between

In the picture x Representative band barrier .
On board volatile The role of is ’ Call constructor ’ Operations of cannot be reordered to ‘ assignment ’ Back , You can avoid getting the class without running the constructor .
边栏推荐
- Vins fusion GPS fusion part
- NVIDIA SMI has failed because it could't communicate with the NVIDIA driver
- PCB走线到底能承载多大电流
- In the future, how long will robots or AI have human creativity?
- Recommend a free intranet penetration open source software that can be used in the local wechat official account under test
- es-ik 安装报错
- KD-Tree and LSH
- Share 𞓜 jointly pre training transformers on unpaired images and text
- jvm调优六:GC日志分析和常量池详解
- 【深入kotlin】 - 初识 Flow
猜你喜欢

Click the icon is not sensitive how to adjust?

JVM tuning V: JVM tuning tools and tuning practice

Using keras to build the basic model yingtailing flower

2021 iccv paper sharing - occlusion boundary detection

Customize the layout of view Foundation

AAAI2022-ShiftVIT: When Shift Operation Meets Vision Transformer

C (I) C basic grammar all in one

Zed2 camera manual

Zed2 camera calibration -- binocular, IMU, joint calibration

Topological sorting
随机推荐
Traversal of binary tree -- restoring binary tree by two different Traversals
深度学习分布式训练
Share | guide language image pre training to achieve unified visual language understanding and generation
Deep search + backtracking
Zed2 running vins-mono preliminary test
js promise,async,await简单笔记
(15) Infrared communication
2021-04-19
MySQL circulates multiple values foreach, XML writing method
Inventory | ICLR 2022 migration learning, visual transformer article summary
Course design summary
[aaai 2021 timing action nomination generation] detailed interpretation of bsn++ long article
Deep learning distributed training
Reverse thinking: making cartoon photos real
[project - what are the supporting materials in the annexes? (18 kinds of 2000 word summary)] project plan of innovation and entrepreneurship competition and supporting materials of Challenge Cup entr
Analysis while experiment - a little optimization of memory leakage in kotlin
在未来,机器人或 AI 还有多久才能具备人类的创造力?
【入门级基础】Node基础知识总结
mysql字符串转数组,合并结果集,转成数组
Why is the smart door lock so popular? What about the smart door locks of MI family and zhiting?