Implementation of pessimistic lock and optimistic lock

Source: Internet
Author: User

Lock (Locking)In the process of implementing business logic, it is often necessary to ensure exclusivity of data access。 As in the final settlement of the financial system, we want to process the data for a cut-off point in time, and we do not want the data to change again during the settlement process (which may be a few seconds or maybe a few hours). At this point, we need to have some mechanism to ensure that the data will not be modified by the outside world during an operation, such a mechanism, in this case, the so-called "lock", that is, to our selected target data locked, so that it cannot be modified by another programHibernate supports two types of locking mechanisms: "Pessimistic lock (pessimistic Locking)" and "optimistic lock (optimistic Locking)". pessimistic Lock (pessimistic Locking)Pessimistic locking, as its name implies, is a conservative attitude to the data being modified by the outside world (including other transactions currently in the system, as well as transactions from external systems), so that the data is locked during the entire data processing process. The realization of pessimistic locks, often rely on the lock mechanism provided by the database(also only the lock mechanism provided by the database tier to truly guarantee the exclusivity of data access, otherwise, even if the locking mechanism is implemented in this system, the external system can not be guaranteedData is not modified). A typical pessimistic lock call that relies on the database: SELECT * from account where name= "Erica" For updateThis SQL statement locks all records in the Account table that match the search criteria (name= "Erica").  These records cannot be modified by the outside world before the transaction commits (the locks in the transaction are freed during transaction commits). Hibernate's pessimistic lock, too implementation of lock mechanism based on database。    The following code implements the locking of the query record: String hqlstr = "from TUser as user where user.name= ' Erica '";    Query query = session.createquery (HQLSTR); Query.setlockmode ("User", Lockmode.upgrade); Locking list userlist = Query.list ();//execute the query, get the data Query.setlockmode lock the records corresponding to a particular alias in the query statement (we have specified an alias "user" for the Tuser Class), This is to lock all the user records returned. observe the SQL statements generated by hibernate during run time: Select Tuser0_.id as ID, tuser0_.name as name, Tuser0_.group_idas group_id, Tuser0_.user_type as User_type, tuser0_.sex a s Sexfrom t_user tuser0_ where (tuser0_.name= ' Erica ') for update hibernate here by using the database The FOR UPDATE clause implements the pessimistic locking mechanismHibernate's Lock modes are:Ølockmode.none: no lock mechanism. Ølockmode.write:hibernate is automatically acquired when the insert and update records are recorded. The ølockmode.read:hibernate is automatically retrieved when the record is read. These three types of locking mechanisms are typically used internally by hibernate, such as hibernate to automatically add write locks to the target object in the Save method implementation, in order to ensure that the object is not modified by the outside world during the update process. Ølockmode.upgrade: Use the database's for UPDATE clause to lock. Ølockmode. A specific implementation of the Upgrade_nowait:oracle, using Oracle's for UPDATE NOWAIT clause to implement the lock. The above two kinds of locking mechanism is more commonly used in the application layer, the lock is generally implemented by the following methods: Criteria.setLockModeQuery.setLockModeSession.lock note that only before the query starts (that is, hiberate  Generate SQL before) set lock, will be really through the lock mechanism of the database lock processing, otherwise, the data has been loaded through a select SQL does not contain a FOR UPDATE clause, so-called database lock also can not be discussed. Optimistic lock (optimistic Locking) relative pessimistic lock, optimistic locking mechanism adopted a more relaxed locking mechanism. Pessimistic locking relies on the lock mechanism of the database in most cases, to ensure the maximum degree of exclusivity of the operation. But that's what comes with it. significant cost of database performance, especially for long-term transactions, that overhead is often unbearable. As a financial system, when an operator reads a user's data and modifies it on the basis of the user's data being read (such as changing the user account balance), the pessimistic locking mechanism means that the entire operation (from the operator reads the data, starts the modification, and commits the modified result.   Even when the operator takes the time to cook the coffee, the database record is always locked, and you can see what happens if you face hundreds of thousand concurrent cases. The optimistic locking mechanism solves this problem to some extent. Optimistic locks, mostly based on Data Versioning (version) recording mechanism implementation。 What is a data version?  is to add a version identity 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 Expired Data。 For the example above to modify user account information, assume that there is a version field in the Account information table in the database, the current value is 1, and the Current Account balance field (balance) is $ $. 1 operator A reads it out at this time (version=1) and deducts $ $100-$50 from its account balance. 2 during operator A's operation, operator B also reads this user information (version=1) and deducts $ $100-$20 from its account balance. 3 operator A has completed the modification work, the data version number plus one (version=2), together with the account deduction after the balance (BALANCE=$50), submitted to the database update, at this time because the submission data version is larger than the current version of database records, the data is updated, database record version updated to 2. 4 operator B completes the operation, and the version number plus one (version=2) attempts to submit data (BALANCE=$80) to the database, but at this time compared to the database record version, operator B submits the data version number 2, the database records the current version is 2, does not meet the " The commit version must be larger than the current version of the record to perform the update "optimistic locking policy, so the submission of operator B is dismissed. This avoids the possibility of operator B overwriting operator A's results with the results of old version=1-based data modifications. As can be seen from the above example, the optimistic locking mechanism avoids the database lock-up overhead in a long transaction (both operator A and operator B do not locking the database data), which greatly improves the overall performance of the system under large concurrent volume. It should be noted that the optimistic locking mechanism is often based on the data storage logic in the system, so there are some limitations, as in the above example, because the optimistic locking mechanism is implemented in our system, the user balance update from the external system is not controlled by our system, it may cause dirty data to be updated into the database. In the system design phase, we should take full account of the possibility of these situations, and make appropriate adjustments (such as the optimistic locking policy implemented in the database stored procedures, external only open the data update path based on this stored procedure, rather than the database table directly to the public). Hibernate has built-in optimistic locking implementations in its data access engine. If you do not take into account the external system to update the database, using hibernate to provide a transparent optimistic lock implementation, will greatly enhance our productivity. Hibernate, you can specified by the Optimistic-lock property of the class descriptor in conjunction with the version descriptor。   Now, let's add an optimistic locking mechanism to the tuser in the previous example. 1. First, add the Optimistic-lock property to the class descriptor for TUser: The current transaction is attempting to submit an expired data。 By catching this exception, we can handle the optimistic lock check when it fails.

Implementation of pessimistic lock and 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.