当前位置:网站首页>Object locking in relational database transactions
Object locking in relational database transactions
2022-07-28 04:24:00 【Navicat China】
summary 、 Lock granularity and deadlock
lately , We have some articles about database transactions , About the enforcement of four ACID attribute ( Atomicity 、 Uniformity 、 Isolation, 、 persistence ). In today's article , We will study relational databases (RDBMS) Used to enforce ACID Another mechanism for attributes , Object locking . say concretely , We will know what it is , It's in RDBMS What role does it play in affairs , And some side effects that locking may cause . Although database object locking can be a fairly technical and complex topic , But we will explain it in plain terms and make it as simple as possible .
What is object locking ?
In short , Object locking is a way to prevent simultaneous access to data in a database , To avoid data inconsistency . To illustrate how object locking works , Suppose two bank tellers try to update the same bank account for two different transactions . Both tellers search ( That is, copy ) Account records . teller A Apply for and save a transaction . teller B Apply different transactions to your saved copies , And save the results , This transaction will cover tellers A Transactions entered . Now the record no longer reflects the first transaction , It's like it never happened !
The fix is to lock the record when any user modifies it , Make it impossible for other users to change it at the same time . This prevents records from being overwritten by mistake , But only one record can be processed at a time , So as to lock other users who need to edit records in the same instance . therefore , Anyone who tries to retrieve the same record for editing will be denied write access because of the lock ( Depends on the implementation , They may still be able to view records in a read-only state ). Once the record is saved ( Or cancel editing ), The lock will be released . Overwrite other changes by preventing the record from being saved , Data integrity (ACID Medium I) Can be maintained .
Lock granularity
The above example demonstrates an example of record level locking . Now imagine , If the above two bank tellers provide services for two different customers , But their accounts are all in the same ledger . under these circumstances , Entire ledger ( perhaps , One or more database tables ) Will need to be locked for editing . As you can imagine , Locking the entire table will cause a lot of unnecessary waiting . If the teller can remove a page from the ledger , It contains the account of the current customer ( There may be some other accounts ), Then it can provide services for multiple customers at the same time , The premise is that each customer's account is located on a different page from other customers . If two customers have accounts on the same page , You can only serve one customer at a time . This is similar to page level locking in a database .
There are four types of locking . Their granularity is getting finer :
- database locked
- Table locking
- Page lock
- Row lock
Locking granularity and deadlock
The use of granularity locking can lead to something called “ Deadlock ” The situation of . When using incremental locking ( Lock an entity , Then lock one or more additional entities ) when , There may be deadlock . for example , My wife and I often transfer money between our personal accounts . If each of us requires tellers to obtain our personal account information , So that we can transfer some money to the other party's account , Then these two accounts will basically be locked . then , When our tellers tried to transfer money into each other's accounts , They will all find another account “ Being used ”, Force them to wait for the account to be released . Before you know it , Two tellers have been waiting for each other , Until the other party gives up returning the account , Neither side can complete the transaction ! thankfully , Some people have designed various technologies to avoid such problems . These will be discussed in the next section .
Pessimism and optimism lock
Relational database system (RDBMS) In the revision ( for example , Update or delete ) Various locking strategies are used to enforce transactions when recording tables ACID attribute . Sometimes , When two concurrent transactions cannot proceed , There may be deadlock , Because every transaction is waiting for the other party to release the lock . In the first of this series 1 In the part , We know what is object locking in relational databases 、 Different types of locks and deadlocks . In today's follow-up article , We will compare the advantages and disadvantages of pessimistic locking and optimistic locking .
Pessimistic lock in
When using pessimistic locking , The resource has been locked since the first access in the transaction , Until the transaction is complete , During this period, other transactions cannot access it . In the case that most transactions only read without updating resources , Exclusive locks may lead to more lock contention ( Deadlock ). Think back to the first 1 Examples of banks in section , Once the account is accessed in the transaction , It will be locked . Any attempt to use this account in other transactions will cause other processes to be delayed , Until the account lock is released , Or the process transaction will be canceled and rolled back to the previous state .
Optimistic locking
When using optimistic locking , Resources are not actually locked when first accessed by transactions . contrary , The initial state of the resource will be persisted . Other transactions can still access the resource , This makes the possibility of conflicting changes a known risk . When committing a transaction , When the resources in the persistent storage are about to be updated , The state of the resource will be read from the storage again , And compare it with the state saved when the resource is accessed for the first time in the transaction . If the two states are different , It means that a conflict update has been made , So the transaction will be rolled back . In our bank example , The amount of the account will be saved on the first visit . If the transaction changes the account amount , Then the amount will be read from the storage again before it is about to be updated . If the amount changes after the transaction starts , The transaction itself will fail , Otherwise, the new amount will remain unchanged and saved .
Decide between pessimistic locking and optimistic locking
Now that we have introduced what the two types of locking are , The question becomes which one should be used . in the majority of cases , Optimistic locking is more effective and provides higher performance . meanwhile , Pessimistic locking provides better data integrity , however , Locking management is more difficult , Because it is more likely to encounter deadlock . When choosing between pessimistic locking and optimistic locking , Please consider the following three guidelines :
- If there are a lot of updates and users try to update data at the same time, the chance is relatively high , Pessimistic locking is very useful .
- Pessimistic locking is more suitable for applications that contain small tables that are updated frequently . In these “ hotspot ” Under the circumstances , The possibility of conflict is very high , So optimistic locking wastes the effort to rollback conflicting transactions .
- When the probability of conflict is very low , Optimistic locking is useful , That is, there are many records but relatively few users , Or it is rarely updated but mainly read .
Avoid or minimize deadlocks
In relational database system (RDBMS) in , A deadlock is a situation where two concurrent transactions cannot proceed , Because every transaction is waiting for another to release the lock . In the first of this series 1 In the part , We know what is object locking in relational databases 、 Different types of locks and deadlocks . then , In the 2 In the part , We compared the advantages and disadvantages of pessimistic locking and optimistic locking . In this article , We will explore several causes of deadlock , And strategies to avoid or at least minimize deadlocks .
Inefficient query
Deadlock is inevitable to some extent , But as long as one of the two transactions ends in time , Deadlock will rarely happen and will not lead to disaster . The fact proved that , One of the most common sources of congestion problems is tedious and inefficient SQL sentence , These statements will cause the database to run “ Hang up ”. These can be remedied in two steps :
- Optimize poor performance SQL sentence , In order to release the lock in the shortest time .
- Perform any long-running SQL The statement before , Identify whether the lock can be released .
for example , If due to execution DELETE Statement to obtain the lock , And it is followed by a full table scan SELECT sentence , You should decide whether you can execute between them COMMIT sentence . This should help release the lock earlier .
Nested transactions
Another common cause of blocking problems is that sleep sessions have lost track of transaction nesting levels . for example , If the application cancels SQL Statement or timeout but not issued COMMIT or ROLLBACK sentence , Then the resource may remain locked indefinitely . Some ways to deal with this problem include :
- After any application errors , Submit in the application's error handler [email protected]@TRANCOUNT > 0 ROLLBACK TRAN sentence .
- Include in any stored procedure that starts a transaction SET XACT_ABORT ON sentence , Especially if they are not cleaned up after the error . By doing so , If a runtime error occurs , Any open transaction will abort and return control to the client .
- If the connection pool is used by an application that opens connections and runs some queries before returning connections to the pool , Then you may need to consider temporarily disabling connection pooling . By doing so , The database server connection is physically logged off , Cause the server to rollback any open transactions .
Get some results
A little-known source of deadlocks is applications that do not get all result lines at once . That's a problem , Because when the query has been sent to the server , The application must be able to get all the result rows to complete the query . If this hadn't happened , The table will be locked , This will cause other users to block . therefore , Please try encoding your application , So that they can get all the rows they need , Instead of dispersing it into multiple iterations .
Looking back
Navicat Poisoned | The truth is coming !
Equipment paralysis caused by piracy
Navicat 16.1 by OceanBase Community Edition
Navicat Become a member of the database Innovation Laboratory of the Academy of communications
Navicat Academic partnership program - Free education application
Navicat Technology think tank - Practical exercises and answers to various hot questions
Free trial introduction | Navciat 16 Database management tools
边栏推荐
- Kotlin——函数
- Thoroughly understand the sharing function in wechat games
- About me writing a custom cell
- Information system project manager (2022) - key content: Strategic Management (17)
- Learn regular expressions (regexp)
- Some personal understandings of openpose
- Idea2022 change the local warehouse and configure Alibaba cloud central warehouse
- Citrix virtual desktop tcp/udp transmission protocol switching
- RT thread changes the print serial port (add other functions on the basis of BSP)
- Filters, interceptors, listeners
猜你喜欢

idea启动项目mvn命令终端用不了法将“mvn”项识别为 cmdlet

10 more advanced open source command line tools

ServletContext、request、response

@Requiredargsconstructor annotation

重要的 SQL Server 函数 - 其他函数

JDBC usage

RT thread changes the print serial port (add other functions on the basis of BSP)

openpose的一些个人理解

21 days, fat brother personally takes you to play oauth2

Idea2022 change the local warehouse and configure Alibaba cloud central warehouse
随机推荐
Experience sharing of automatic test for students with monthly salary of 28K
Domestic high hidden free agent crawler code
Information system project manager (2022) - key content: Information System Security Management (20)
We must do these seven things well before leaving, and it's troublesome to do one less thing.
pl/sql之各参数详解(“箱子模型“)
虚拟机类加载机制
Difference between on, where and having
jdbc使用
Combination of Oracle and Premier League statistics and presentation
[untitled]
Esp8266 WiFi module and mobile communication
setup和hold timing分析不满足是解决方法
There are so many ways to view the web source code! Do you know?
Un7.27: common commands of redis database.
Docking with Hang Seng express ― dolphin DB NSQ plug-in tutorial
上班摸鱼打卡模拟器微信小程序源码
How to select reliable securities analysts?
Kingbasees Security Guide for Jincang database -- 6.1 introduction to strong authentication
Thoroughly understand the sharing function in wechat games
Seamless support for hugging face community, colossal AI low-cost and easy acceleration of large model