The difference between optimistic locking and pessimistic locking

definition

Pessimistic Lock

As the name suggests, it is very pessimistic. Every time I go to get the data, I think that others will modify it, so every time I get the data, it will be locked, so that if someone wants to get the data, it will block until it gets the lock. Many such lock mechanisms are used in traditional relational databases, such as row locks, table locks, read locks, write locks, etc., all of which are locked before operations are performed. It refers to a conservative attitude towards data being modified by the outside world (including other current transactions in the system, as well as transactions from external systems), so that the data is locked during the entire data processing process. The implementation of pessimistic locks often relies on the locking mechanism provided by the database (only the locking mechanism provided by the database layer can truly guarantee the exclusivity of data access. Otherwise, even if the locking mechanism is implemented in this system, it cannot be guaranteed that the external system will not be modified. data).

Optimistic Lock

As the name implies, it is very optimistic. Every time I go to get the data, I think that others will not modify it, so it will not be locked, but when it is updated, it will judge whether others have updated the data during this period. You can use the version number, etc. mechanism. Optimistic locks are suitable for multi-read application types, which can improve throughput. For example, if the database provides a mechanism similar to write_condition, it is actually an optimistic lock.

the difference

Both types of locks have their own advantages and disadvantages, and one cannot be considered better than the other. For example, optimistic locks are suitable for the case where there are few writes, that is, when conflicts really rarely occur, which can save the overhead of locks, plus increase the overall throughput of the system. However, if conflicts occur frequently, the upper-layer application will continue to retry, which will reduce performance, so it is more appropriate to use pessimistic locks in this case.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326356680&siteId=291194637