当前位置:网站首页>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 .
边栏推荐
- Wechat applet - basic content
- flinksql是可以直接客户端建表读mysql或是kafka数据,但是怎么让它自动流转计算起来呢?
- Kubernetes three dozen probes and probe mode
- How to convert a numeric string to an integer
- C language improvement article (wchar_t) character type
- 102. Sequence traversal of binary tree
- 使用BLoC 构建 Flutter的页面实例
- 145. Post order traversal of binary tree
- pragma-pack语法与使用
- Computer version wechat applet full screen display method, mobile phone horizontal screen method.
猜你喜欢

Laravel time zone timezone

Unicode encoding table download

Itext7 uses iexternalsignature container for signature and signature verification

Swagger

Summary of development issues

QT OpenGL texture map

Display time with message interval of more than 1 minute in wechat applet discussion area

Shutter: overview of shutter architecture (excerpt)

Shutter widget: centerslice attribute

Colleagues wrote a responsibility chain model, with countless bugs
随机推荐
How to convert a numeric string to an integer
Develop plug-ins for idea
Qt+vtk+occt reading iges/step model
239. Sliding window maximum
OpenGL shader use
2.9 overview of databinding knowledge points
2.7 overview of livedata knowledge points
Adult adult adult
Dart: About zone
Solutions to the failure of installing electron
242. Effective letter heteronyms
1-1 token
Symlink(): solution to protocol error in PHP artisan storage:link on win10
shardingSphere分库分表<3>
OpenGL index cache object EBO and lineweight mode
Simple factory and factory method mode
AOSP ~ NTP (Network Time Protocol)
2.8 overview of ViewModel knowledge
JVM memory model
Vulnhub pyexp