当前位置:网站首页>Multithreading and high concurrency II: detailed introduction to volatile and CAS
Multithreading and high concurrency II: detailed introduction to volatile and CAS
2022-06-28 04:14:00 【smartjiang-java】
List of articles
1: I said synchronized, But locking generally reduces efficiency , Then there was lock optimization .
2: There are two kinds of lock optimization
Lock refinement : The fewer statements in the synchronized code block, the better , Lock only the code that needs to be synchronized
Lock coarsening : Several fine locks have been added to the code , It's better to put a lock in the big block , Reduce code contention
3: But the problem of efficiency can still be solved in a better way . For example, use volatile and CAS, Also known as no lock , As for whether it is a lock or not , It's good to understand .
1:volatile The role of
1.1: Ensure the visibility of variables between threads
All threads will read the modified value of the variable . Threads share heap memory , But each thread has its own memory . When two threads access variables in heap memory , First of all copy One copy into your own memory , Thread one changed this variable , First, modify in your own memory , When will the modification of this variable be written back to the heap memory , It's not easy to control .( At this point, the variable has been modified ), The variable value read by thread 2 is still the initial value , Changes made by thread 1 to variables cannot be reflected in thread 2 in time . added volatile, Used cpu Cache consistency protocol for (MESI), Guaranteed visibility .
1.2: Disable instruction reordering
Previous instructions were loaded sequentially into cpu in , Step by step . But now cpu In order to improve efficiency , Will execute instructions concurrently . For example, when the first instruction is half executed , The second instruction has already been executed , The third instruction also begins ( Pipelined execution ).
example 1( For example , The actual scene does not necessarily happen ):
Int a=5;
a=2;
a=4;
According to logic a May be 5->2->4 The change of , But if there is an instruction sort , There may be 5->4->2 The change of
example 2:
new A new object has three steps
-JVM Apply for a piece of memory , Give member variables default values a=0
- Initialization of member variables a=8
- Let the variable point to the address of the object
In double check singleton mode ( Superelevation may occur ): No addition volatile, Thread one may initialize one a=0 The object of ( Instruction reordering ), Thread 2 will get this a=0 The object of , Cannot get a value of 8 Member variables of
1.3: shortcoming : Only visibility but not atomicity
example :
int volatile count =0;
All ten threads execute the following code ,count added volatile, Ensure variable visibility between threads .
for(int i=0;i<10000;i++){
count ++;
}
Print after executing the code count Value , But not a hundred thousand .
There are two ways to solve :
aa: to count++; Statement lock ,synchronized You can guarantee atomicity , But the efficiency is reduced , But here's the proof volatile There is no substitute for synchronized
bb: Use CAS、
cc: Use classes that specifically solve integer problems LongAdder( With the sectional lock , Section lock is also CAS operation )
2:CAS Detailed introduction
2.1:CAS brief introduction
CAS Also called spin lock , Optimism lock : Lock free optimization , stay JVM There is no lock on the layer , But in cpu The floor is still locked , yes CPU Primitives support . adopt lock cmpxchg Order to complete ,lock The command locks a North Bridge signal when executing the following command , stay cas When the comparison is completed and the new value is written, the lock is applied .
2.2: CAS principle
(Compare And Set)
There are three values : Value to modify (V1), Expected value (V2), Set new value (P) . Only when V1=V2 when , Only then V1 To change the value of P Value
2.3:CAS Caused by the ABA problem
Take an inappropriate but understandable example ( I forgot what I saw on that blog ):
Xiao Ming has a girlfriend (V1), Xiaoming's mother wants to meet Xiaoming's girlfriend (V2), If mom thinks it's appropriate , I decided that she was Xiao Ming's girlfriend (P).
Xiao Ming prepares 10 month 1 My girlfriend took it home , But we broke up in the middle , My girlfriend is with Xiao Li , Later, I broke up with Xiao Li and got along with Xiao Huang , Finally, I broke up with Xiao Huang again , I turned back to Xiao Ming .
that : Girlfriend or that girlfriend , But I always felt something was wrong .
resolvent :
aa: Add the version number to each version of the data , When comparing, not only compare the data , Also compare the version number
bb: Atomic classes have AtomicStampedReference Class specifically addresses ABA problem ( Want to know more about yourself , Novice bloggers are not enough )
2.4: Atomic classes (AtomXXX class )
It's common to see AtomInteger class , The implementation principle uses CAS. In the atomic class Compare And Set Is in Unsafe This class ( Equate to c,c++ The pointer ) Implemented in , This class is implemented in singleton mode .jdk8 Can't call directly getUnsafe() Method , Using this object . But in jdk11 It can be called directly , And will Compare And Set Changed to WeakCompare And Set, Strengthen the garbage collection mechanism ( You can learn more about it by yourself ).
Be careful : This article only represents the personal views of novice bloggers , If something is wrong or there is a better idea through the technology , Welcome to leave a message , Sharing and communication make us progress , thank you .
边栏推荐
- Tiktok actual battle ~ take off the blogger
- 云厂商为什么都在冲这个KPI?
- In the era of video explosion, who is supporting the high-speed operation of video ecological network?
- Little knowledge about function templates --
- 内卷、躺平与中年危机的相关思考
- 简单工厂模式
- Detailed explanation of KVM common commands
- 从零到一,教你搭建「以文搜图」搜索服务(一)
- 2021 year end summary and 2022 outlook
- MSC 307(88) (2010 FTPC Code) Part 9床上用品试验
猜你喜欢

sqlserver 数据库之事物使用入门 案例

品达通用权限系统(Day 5~Day 6)

公司领导说,个人代码超10个Bug就开除,是什么体验?

Chapter 14 AC-DC power supply front stage circuit note I

Market competitiveness of robot programming education

La norme européenne en 597 - 1 pour les meubles est - elle la même que les deux normes en 597 - 2 pour les ignifuges?

Multi project design and development · introduction to class library project

阿里P8倾情推荐,Fiddler抓包工具实战篇(一)

测试/开发程序员真的是青春饭吗?世界是公平的,咱们都凭实力说话......

How to learn a programming language systematically| Dark horse programmer
随机推荐
@Several scenarios of transactional failure
Detailed explanation of KVM common commands
GenICam GenTL 标准 ver1.5(2)
《性能之巅第2版》阅读笔记(二)--性能观察工具
Pinda general permission system (day 5~day 6)
RT thread bidirectional linked list (learning notes)
How to learn a programming language systematically| Dark horse programmer
多项目开发入门,基础设计 类库项目使用
04 summary of various query operations and aggregation operations of mongodb
MSc 307 (88) (2010 FTPC code) Part 2 smoke and toxicity test
美创数据安全管理平台获信通院“数据安全产品能力验证计划”评测证书
MSC 307(88) (2010 FTPC Code)第2部分烟气和毒性测试
Understanding and learning of parental delegation mechanism
《性能之巅第2版》阅读笔记(二)--CPU监测
Chapter 1 Introduction to bash
La norme européenne en 597 - 1 pour les meubles est - elle la même que les deux normes en 597 - 2 pour les ignifuges?
03 summary of various additions, updates and deletions of mongodb documents
第一个.net core MVC项目
02 mongodb data types, important concepts and common shell instructions
11_ Deliberate practice and elaboration