Basic understanding of MySql pessimistic locking and optimistic locking

Understanding of pessimistic locks and optimistic locks in MySQL

1. Pessimistic locks
Pessimistic locks, as the name implies, are all locked up,
such as
select *from t_order where id=101 or id=102 or id=103 for update
The for update parameter tells the database where to read All the data in the condition is locked, any read or update operations are prohibited, the rest of the operations enter the block to wait, and the lock is released directly

Advantages : It can ensure the consistency of data
Disadvantages: The disadvantage is that all queries must wait for the lock Or, if there are too many queries, the database connection will be blocked all the time, and the number of connections will be large, which may cause the database connection to time out

. 2. Optimistic locking
Optimistic locking is actually another name given by programmers to pessimistic locks. Members add logic processing by themselves.
For example
update t_goods set count = count - ${count} where id=1 count > ${count}
is equivalent to using the count field as the version field when the update is executed. At this time, it can be guaranteed that when the count is updated, the count The number must be greater than the parameter ${count}, which ensures the maximum operating efficiency. Only when count > ${count} will conflicts really occur.

Of course, an independent version can also be used as an identifier
. , update version+1 when the execution is complete, if there is a conflict in the version, the execution fails
select (status,status,version) from t_goods where id=#{id}

update t_goods
set status=2,version=version+1
where id=#{id} and version=#{version};

Advantages: At this time, it is generally applicable to the scenario where the query fails to execute after the query, to ensure that the query is not controlled by locks.
Disadvantages : Large-scale conflicts caused by large concurrency will lead to more failed rollback operations

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326720953&siteId=291194637
Recommended