当前位置:网站首页>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 .
边栏推荐
- 424. The longest repeated character after replacement ●●
- 424. 替换后的最长重复字符 ●●
- Development specification: interface unified return value format [resend]
- 【经典控制理论】自控实验总结
- Idea rundashboard window configuration
- Dynamic memory management (malloc/calloc/realloc)
- 698. Divided into k equal subsets ●●
- Neural structured learning 4 antagonistic learning for image classification
- 【原创】程序员团队管理的核心是什么?
- 4点告诉你实时聊天与聊天机器人组合的优势
猜你喜欢
如何获取localStorage中存储的所有值
如何让同步/刷新的图标(el-icon-refresh)旋转起来
成为程序员的你,后悔了吗?
4 points tell you the advantages of the combination of real-time chat and chat robots
Attacking technology Er - Automation
Spécifications techniques et lignes directrices pour la sélection des tubes TVS et ESD - Recommandation de jialichuang
Rasa 3. X learning series -rasa x Community Edition (Free Edition) changes
STM32__ 06 - single channel ADC
Fiddler Everywhere 3.2.1 Crack
Redis高可用——主从复制、哨兵模式、集群
随机推荐
Data analysis - Thinking foreshadowing
It is proved that POJ 1014 module is optimized and pruned, and some recursion is wrong
做自媒体影视短视频剪辑号,在哪儿下载素材?
What is the process of building a website
(4) UART application design and simulation verification 2 - RX module design (stateless machine)
LeetCode——Add Binary
Spire Office 7.5.4 for NET
The interface of grafana tool displays an error, incluxdb error
regular expression
Design and implementation of secsha system
成为程序员的你,后悔了吗?
How to enable relationship view in phpMyAdmin - how to enable relationship view in phpMyAdmin
21.PWM应用编程
idea 连接mysql ,直接贴配置文件的url 比较方便
grafana工具界面显示报错influxDB Error
yate.conf
424. The longest repeated character after replacement ●●
Xinyuan & Lichuang EDA training camp - brushless motor drive
Spécifications techniques et lignes directrices pour la sélection des tubes TVS et ESD - Recommandation de jialichuang
Calculating the number of daffodils in C language