First, the optimistic lock (optimistic locking) and pessimistic lock (pessimistic locking) is basically for data processing, that is, the terminology associated with the database, the purpose is to solve the concurrency of the related performance problems encountered in order to avoid data loss updates.
Pessimistic lock (pessimistic locking): refers to the data by the outside (including the system's current other transactions, as well as the transaction from the external system) is conservative attitude, therefore, throughout the data processing process, will be locked in order to ensure the maximum degree of exclusivity of operation, Of course, it also adds a lot of overhead to the database to reduce performance. Generally rely on the database provides the lock mechanism (also only the database layer provides the lock mechanism to truly guarantee the exclusivity of data access, otherwise, even in this system to implement the locking mechanism, there is no guarantee that the external system will not modify the data).
optimistic Lock (optimistic locking) : refers to the adoption of a more lenient locking mechanism. It is used to solve the overhead performance problems caused by pessimistic locking mechanism. Optimistic locks, mostly based on the version record mechanism, are implemented by adding a version identifier to the data, which is typically done by adding a "version" field to the database table in the version solution based on the database table. When the data is read, the version number is read together, and then the version number is added one after the update. At this point, the version data of the submitted data is compared to the current version information of the database table corresponding to the record, and if the submitted version number is greater than the current version number of the database table, it is updated, otherwise it is considered to be outdated data.
In the actual production environment, if the concurrency is not large and dirty reading is not allowed, pessimistic locking can be used to solve the concurrency problem, but if the system concurrency is very large, it is necessary to choose optimistic locking method.
Optimistic lock (optimistic locking) with pessimistic lock (pessimistic locking)