当前位置:网站首页>CAS and synchronized knowledge
CAS and synchronized knowledge
2022-07-05 23:39:00 【Archie_ java】
One . CAS
What is the CAS.
CAS(Compare And Swap ) It's an implementation of optimistic lock , It's a lightweight lock .JAVA1.5 It's starting to introduce CAS,JUC Many tool classes are based on CAS.
CAS How to implement
CAS Yes 3 Operands , Memory value V, Old expectations A, New value to modify B. If and only if expected A And memory values V Phase at the same time , Put the memory value V It is amended as follows B, Otherwise, do nothing . When multiple threads try to use CAS When updating a variable , Only one thread can update successfully at any time , If the update fails , The thread will re-enter the loop and try again .
CAS stay Java Application in
I said that before JUC Many tool classes below are used CAS. It mainly depends on Unsafe Of CAS Operation to realize .
for example AtomicInteger Under the incrementAndGet operation :
Let's take a look at Unsafe Under the getAndAddInt Method
You can see Unsafe In the loop body, first read the in memory value value , then CAS to update , If CAS If the update is successful, exit , If the update fails , Then retry circularly until the update succeeds .
CAS The problems brought about by
ABA problem
For example, :
One . Threads 1 Whether the query value is A
Two . Threads 2 Whether the query value is A
3、 ... and . Threads 2 Use CAS Update the value to B
Four . Threads 2 Whether the query value is B
5、 ... and . Threads 2 Use CAS Update the value to A
6、 ... and . Threads 1 Use CAS Update the value to C
Thread one and thread two execute alternately . Step 2 to step 5 , Thread 2 sets the value from A Updated to B From to A, But the thread didn't notice , Therefore, thread one can continue to execute . We call this phenomenon ABA problem .
resolvent :
Use version number ( Time stamp ), Every time you perform data modification , They all carry a version number , Once the version number is consistent with the version number of the data, you can perform the modification operation and add one to the version number , Otherwise, the execution fails . for example AtomicStampedReference By adding a stamp to the value (stamp) To solve “ABA” The problem of .
The cycle overhead is too high
CAS If the operation is unsuccessful , Will cause constant spin ,CPU There will be a lot of pressure . For example, Unsafe Under the getAndAddInt The method will always loop , It won't return until success .
Only atomic operation of one variable can be guaranteed
Two . synchronized
Compared with CAS Based on optimistic lock implementation ,synchronized It is based on pessimistic lock , When a thread tries to access a synchronized block of code , It must first get the lock , The lock must be released when exiting or throwing an exception .
When locking with common synchronization methods , The lock is the current instance object .
When locking the static synchronization method , The lock is for the current class Class object .
For synchronous method block locking , The lock is Synchonized Objects configured in parentheses .
Synchronized How to implement :
Synchonized It's based on entry and exit Monitor Object to synchronize methods and code blocks , But the implementation details of the two are different .Synchronized When used in methods , In bytecode, it is through method ACC_SYNCHRONIZED Logo to achieve . Code block synchronization uses monitorenter and monitorexit Instruction implementation .
monitorenter Instructions are inserted at the beginning of a synchronized block of code after compilation , and monitorexit Is inserted at the end of the method and at the exception ,JVM Make sure that each monitorenter There must be a corresponding monitorexit Match it . Any object has one monitor Associated with it , When and one monitor After being held , It will be locked . Thread execution to monitorenter When the command , Will try to get the corresponding monitor The ownership of the , That is, trying to get the lock of the object , When getting the object monitor in the future ,monitor The internal counter will automatically increase ( For the initial 0), When the same thread gets monitor When , The counter will self increment again . When the same thread executes monitorexit At the time of instruction , The counter will automatically decrease , When the counter is 0 When ,monitor Will be released , Other threads can get monitor.
Synchronized The optimization of the
Java SE 1.6 In order to reduce the performance consumption of acquiring lock and releasing lock , Introduced “ Biased locking ” and “ Lightweight lock ”, stay Java SE 1.6 in , There's a lock 4 States , The order of rank from low to high is : No lock state 、 Biased lock state 、 Lightweight lock state and heavyweight lock state .
Biased locking
When a thread accesses a synchronization block and acquires a lock , The thread with lock bias will be stored in the lock record in the object header and stack frame ID, In the future, the thread does not need to enter or exit the synchronization block CAS Operate to lock and unlock , Just test the head of the object Mark Word Whether there are biased locks pointing to the current thread stored in . If the test is successful , Indicates that the thread has acquired the lock . If the test fails , It needs to be tested again Mark Word Whether the sign of the middle biased lock is set to 1( Indicates that the current lock is biased ), If not set , Then use CAS Competitive lock ; If set , Then try to use CAS Point the biased lock of the object header to the current thread .
Lightweight lock
Thread before executing synchronization block ,JVM The space used to store the lock record will be created in the current thread's stack frame first , And Mark Word Copy to lock record . Then the thread tries to use CAS Put the Mark Word Replace with a pointer to the lock record . If it works , Current thread gets lock , If you fail , Indicates that other threads are competing for locks , The current thread attempts to acquire a lock using spin .
Heavyweight lock
Heavyweight locks depend on the inside of the object monitor Lock to achieve . When the system checks that the lock is a heavyweight lock , The thread waiting for the lock will be blocked , Blocked threads don't consume cup. But when you block or wake up a thread , You need the operating system to help , Need to switch from user mode to kernel mode , And switching states takes a lot of time .
边栏推荐
- The PNG image is normal when LabVIEW is opened, and the full black image is obtained when Photoshop is opened
- UVA – 11637 garbage remembering exam (combination + possibility)
- Creative mode 1 - single case mode
- 15 MySQL-存储过程与函数
- Neural structured learning 4 antagonistic learning for image classification
- Switching power supply buck circuit CCM and DCM working mode
- Go language implementation principle -- lock implementation principle
- 如何让同步/刷新的图标(el-icon-refresh)旋转起来
- Opencvsharp (C openCV) shape detection and recognition (with source code)
- Hcip course notes-16 VLAN, three-tier architecture, MPLS virtual private line configuration
猜你喜欢
98. 验证二叉搜索树 ●●
Neural structured learning - Part 2: training with natural graphs
21.PWM应用编程
Switching power supply buck circuit CCM and DCM working mode
GFS distributed file system
开源crm客户关系统管理系统源码,免费分享
Dynamic memory management (malloc/calloc/realloc)
Spécifications techniques et lignes directrices pour la sélection des tubes TVS et ESD - Recommandation de jialichuang
保研笔记一 软件工程与计算卷二(1-7章)
Neural structured learning - Part 3: training with synthesized graphs
随机推荐
Opencvsharp (C openCV) shape detection and recognition (with source code)
asp.net弹出层实例
UVA – 11637 Garbage Remembering Exam (组合+可能性)
动态规划 之 打家劫舍
保研笔记二 软件工程与计算卷二(13-16章)
4 points tell you the advantages of the combination of real-time chat and chat robots
代码农民提高生产力
Switching power supply buck circuit CCM and DCM working mode
Naoqi robot summary 26
Dynamic memory management (malloc/calloc/realloc)
From the perspective of quantitative genetics, why do you get the bride price when you get married
Solution to the packaging problem of asyncsocket long connecting rod
Pyqt control part (I)
Huawei simulator ENSP - hcip - MPLS experiment
保研笔记四 软件工程与计算卷二(8-12章)
(4) UART application design and simulation verification 2 - TX module design (stateless machine)
证明 poj 1014 模优化修剪,部分递归 有错误
Research notes I software engineering and calculation volume II (Chapter 1-7)
yate.conf
Rasa 3.x 学习系列-Rasa X 社区版(免费版) 更改