当前位置:网站首页>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 .
边栏推荐
- 基于正点原子stm32的mini板的TFTLCD显示实验
- Little knowledge about function templates --
- Meichuang was selected into the list of "2022 CCIA top 50 Chinese network security competitiveness"
- 多项目设计开发·类库项目引入入门
- MSC 307(88) (2010 FTPC Code) Part 5低播焰测试
- 2022年6月对自己近况的一次总结
- Learning notes of digital circuit (II)
- first. Net core MVC project
- 云厂商为什么都在冲这个KPI?
- Zipkin service link tracking
猜你喜欢
MSC 307(88) (2010 FTPC Code)第2部分烟气和毒性测试
Uncover the mystery of SSL and learn how to protect data with SSL
GO语言-select语句
Analyzing the comprehensive application ability of educational robot
One article tells you what kubernetes is
Little knowledge about function templates --
A summary of my recent situation in June 2022
In the era of video explosion, who is supporting the high-speed operation of video ecological network?
GenICam GenTL 标准 ver1.5(2)
利用 telegraf influxdb grafana 搭建服务器监控平台
随机推荐
Design a stack with getmin function
Learning notes of digital circuit (II)
Leetcode: monotonic stack structure (Advanced)
MSc 307 (88) (2010 FTPC code) Part 5 low flame spread test
2021年终总结及2022年展望
What are the password requirements for waiting insurance 2.0? What are the legal bases?
01 overview, application scenarios, Download methods, connection methods and development history of mongodb
光伏板怎么申请ASTM E108阻燃测试?
简单工厂模式
《性能之巅第2版》阅读笔记(二)--性能观察工具
Analyzing the comprehensive application ability of educational robot
Introversion, lying flat and midlife crisis
Several important physical concepts
How to learn a programming language systematically| Dark horse programmer
欧洲家具EN 597-1 跟EN 597-2两个阻燃标准一样吗?
03 MongoDB文档的各种增加、更新、删除操作总结
美创入选“2022 CCIA中国网络安全竞争力50强”榜单
Web APIs DOM event foundation dark horse programmer
Chapter 1 Introduction to bash
A summary of my recent situation in June 2022