当前位置:网站首页>02_ Lock the code, and don't let the "lock" become a worry
02_ Lock the code, and don't let the "lock" become a worry
2022-07-03 12:24:00 【jackaroo2020】
I. Code locking
1. Before locking, it should be clear whether the lock and the protected object are at the same level
Static fields belong to classes , Class level lock can protect ; Non static fields belong to class instances , Instance level locks can protect .
2. The granularity and scenario of locks should be considered in locking
Add... To the method synchronized Keyword locking is really simple , Therefore, I have seen that almost all methods in some business code have been added synchronized, But this abuse synchronized How to do it :
One is , It is not necessary to . Usually 60% The business code of is a three-tier architecture , Data goes through stateless Controller、Service、Repository Flow to database , There is no need to use synchronized To protect what data .
Two is , Can significantly degrade performance . Use Spring When the framework , By default Controller、Service、Repository Is a singleton , add synchronized It will cause the whole program to support almost single thread , Cause a huge performance problem .
Even if we do have some shared resources to protect , Also try to reduce the granularity of the lock as much as possible , Lock only the necessary code blocks or even the resources that need to be protected .
If refinement considers the scope of lock application , If the performance cannot meet the requirements , We have to consider the granularity of another dimension , namely : Distinguish between read-write scenarios and resource access conflicts , Consider using pessimistic locks or optimistic locks .
General business code , There is little need to consider these two finer grained locks further , You can consider whether it is necessary to further optimize according to your own needs :
For scenes with obvious differences in reading and writing ratio , Consider using ReentrantReadWriteLock Refine and distinguish read-write locks , To improve performance .
If your JDK Version higher than 1.8、 If the conflict probability of shared resources is not so high , Consider using StampedLock The characteristics of optimistic reading , Further improve performance .
JDK in ReentrantLock and ReentrantReadWriteLock Both provide versions of fair locks , Don't open the fair lock feature easily without clear requirements , When the task is very light, opening the fair lock may reduce the performance by hundreds of times .
3. Be careful of deadlocks when locking more
The third is , Not fully understand the characteristics of concurrency tools , Still use the new tool in the old way, so it can't play its performance . such as , Used ConcurrentHashMap, However, it did not make full use of the information it provided based on CAS A safe way , Or use locks to implement logic .
Use JDK Self contained VisualVM Tools to track , Soon after re executing the method, you can see , Threads Tab The deadlock problem is prompted in , Click the thread on the right according to the prompt Dump Button to perform thread grabbing operation .
II. Focus on
First of all , Use synchronized Locking is simple , But first we need to find out whether shared resources are class or instance level 、 Which threads will be operated by ,synchronized The scope of the associated lock object or method .
second , When locking, consider granularity and scenario as much as possible , Lock protected code means that multithreading is not possible . about Web Type of natural multithreaded project , Locking methods in a wide range can significantly degrade concurrency , Consider locking only the necessary blocks of code as much as possible , Reduce lock granularity ; For businesses that require ultra-high performance , We should also refine the read-write scenario considering locks , And whether pessimism comes first or optimism comes first , Try to refine the locking scheme for specific scenes , Consider using... In appropriate scenarios ReentrantReadWriteLock、StampedLock And other advanced lock tools .
Third , Deadlock should be considered when there are multiple locks in business logic , The usual solution is , Avoid infinite waiting and circular waiting .
Besides , If the implementation of locks in business logic is complex , Look carefully to see if locking and releasing are paired , Whether there is the possibility of missing release or repeated release ; And for distributed locks, it should be considered that the lock is automatically released over time , While the business logic is still in progress , If another thread or process gets the same lock , May result in repeated execution .
III. Supplementary knowledge
1. How to avoid repeating logic after automatically releasing the lock after timeout ?
a. Avoid overtime , Open a separate thread to extend the validity of the lock . For example, set the lock validity 30s, There are threads every 10s Reset the validity of the lock .
b. Avoid repetition , Add a field to the business to mark whether it is processed . Or open a new watch , Save the processed serial number .
2. When the concurrency is not so large , Whether to choose to use when placing an order to deduct inventory version Optimistic locking mechanism , How to design the retry strategy if the update fails with optimistic lock , Avoid the occasional order failure caused by optimistic lock exceptions ?
You can use optimistic locks , Wrong version number , The update operation will fail , Rollback the transaction and retry the current operation . It is recommended to retry at most twice , If you can't order directly, you will fail , Retry by the user .
边栏推荐
- Colleagues wrote a responsibility chain model, with countless bugs
- (构造笔记)GRASP学习心得
- Self made pop-up input box, input text, and click to complete the event.
- JVM memory model
- Differences between MySQL Union and union all
- 网络通讯之Socket-Tcp(一)
- Use of QT OpenGL camera
- [combinatorics] permutation and combination (summary of permutation and combination content | selection problem | set permutation | set combination)
- (construction notes) grasp learning experience
- Vulnhub pyexp
猜你喜欢

If you can't learn, you have to learn. Jetpack compose writes an im app (I)

Solution to the second weekly test of ACM intensive training of Hunan Institute of technology in 2022

Integer string int mutual conversion

1-2 project technology selection and structure

2.7 overview of livedata knowledge points

Cloud Computing future - native Cloud

Shutter: overview of shutter architecture (excerpt)

Wechat applet - basic content

为什么我的mysql容器启动不了呢
![[learning notes] DP status and transfer](/img/5e/59c64d2fe08b89fba2d7e1e6de2761.png)
[learning notes] DP status and transfer
随机推荐
PHP導出word方法(一mht)
2.9 overview of databinding knowledge points
ES6新特性
regular expression
(構造筆記)從類、API、框架三個層面學習如何設計可複用軟件實體的具體技術
The difference between lambda and anonymous inner class
Adult adult adult
(construction notes) learn the specific technology of how to design reusable software entities from three levels: class, API and framework
Introduction to concurrent programming (I)
JVM memory model
C language improvement article (wchar_t) character type
Redis 笔记 01:入门篇
Talk about the state management mechanism in Flink framework
使用BLoC 构建 Flutter的页面实例
previous permutation lintcode51
Jsup crawls Baidu Encyclopedia
Optimize interface performance
QT OpenGL texture map
Dart: about grpc (I)
If you can't learn, you have to learn. Jetpack compose writes an im app (II)