MySQL optimistic lock

Source: Internet
Author: User

MySQL pessimistic lock is based on the lock mechanism of the database to achieve the maximum degree of exclusivity. However, because the modern web system is generally high concurrency, so pessimistic lock in such circumstances, the applicability is not high, so we have a pessimistic lock corresponding to the optimistic lock.

Optimistic lock, that is, when the data to commit the update, the data will be conflicting or not detected, if there is a conflict, then return the wrong information, let the user decide how to do.

The implementation of optimistic locking is generally controlled in the program. There are generally two general implementations: use the data version, which is implemented using timestamps.

Implementation Details:

1. Add a field of version or timestamp field in the table;

2. At the time of the query, return the field, the update, the first check whether the Version field or timestamp field is consistent with the field in the table, if the update is consistent, and the version field plus 1 (timestamp words updated to the current time), if inconsistent indicates that the field has been updated, Prompt for update failure, and then return the error message to the user;

Through some pseudo-code to achieve:

--Pseudo Code:--1. Concurrent query, all query id=1 recordsMysql> SELECT *  fromTest_orderWHEREId= 1;+----+--------+------+----------+---------+-------------+|Id|Status|Name|goods_id|Version|Update_date|+----+--------+------+----------+---------+-------------+|  1 |      1 |Maotai| 123      |       1 | NULL        |+----+--------+------+----------+---------+-------------+1Rowinch Set--2. User 1 Perform the update operationUPDATETest_orderSETStatus=1, version=Version+1 WHEREId=1  andVersion=1 --3. At this point version is 2, user 2 performs the update again, but the update is unsuccessful at this timeUPDATETest_orderSETStatus=1, version=Version+1 WHEREId=1  andVersion=1

The usual SVN is done in a similar way.

MySQL optimistic lock

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.