Optimistic locking

Optimistic lock adopts a more relaxed locking mechanism. Optimistic locking is a mechanism to avoid data processing errors caused by database illusionary reading and long service processing time. However, optimistic locking does not deliberately use the locking mechanism of the database itself, but ensures the correctness of data according to the data itself.

-- Optimistic Lock: You are optimistic and assume that no one will change your data every time you go to get it. If num is changed, the update will not succeed. 1, select num as num_1 from user where id =1; 2, Update user set name='zhangsan',num=(num+1) where id=1 and num=num_1; The key is to query first, then conditionCopy the code

Pessimistic locking

Pessimistic locks, as the name suggests, are intensely exclusive and exclusive. It refers to the conservative attitude toward data being modified by other transactions currently in the system, as well as transactions from external systems. Therefore, the data is locked throughout the data processing process. The realization of pessimistic lock, often rely on the locking mechanism provided by the database (only the locking mechanism provided by the database layer can truly ensure the exclusivity of data access, otherwise, even if the locking mechanism is implemented in this system, it can not guarantee that the external system will not modify the data).

Pessimistic locking: Assume that every time data is fetched, a lock is placed on a row or table in the database in the expectation that it will be modified. Note that for update must be used on the index, otherwise the table will lock. 1, START the TRANSACTION; 2, select * from USER where id=1 for update; 3, UPDATE USER SET name= 'zhangsan' WHERE id = 1; 4, COMMIT; The key is the for Update database lockCopy the code