Optimistic lock and pessimistic lock in concurrency control

Source: Internet
Author: User
Tags commit versions
Why locks (concurrency control) are required.

In a multiuser environment, multiple users may update the same record at the same time, which can create a conflict. This is the famous concurrency problem.

Typical conflicts are:
(1) Missing update: One transaction update overwrites the update result of other transactions, that is, the so-called update is lost. For example: User A changes the value from 6 to 2, and User B changes the value from 2 to 6, then user a loses his update.

(2) Dirty read: Dirty reads occur when a transaction reads a record of another half-completed transaction. For example, the user A, B sees a value of 6, the value is changed to 2, and the value read by user A is still 6. concurrency control mechanism

pessimistic lock : it is assumed that concurrency conflicts occur and that all operations that may violate data integrity are masked.
optimistic lock : Assume that there will be no concurrency conflicts and only check for violation of data integrity when committing the operation. Optimistic locking does not solve the problem of dirty reading. optimistic lock and pessimistic lock

Pessimistic lock (Pessimistic lock), is very pessimistic, every time to take the data when they think others will change, so every time when the data are locked, so that people want to take this data will block until it gets the lock. Traditional relational database in the use of a lot of this locking mechanism, such as row locks, table locks, read locks, write locks, etc., are in operation before the lock.

optimistic Lock (Optimistic Lock), as the name implies, is very optimistic, every time to take the data when they think others will not be modified, so will not be locked, but in the update will be judged in the period when others have to update this data, you can use the version number and other mechanisms. Optimistic locking is useful for multi-read application types, which can improve throughput, such as the fact that a database provides an optimistic lock similar to the write_condition mechanism.

Two kinds of locks have advantages and disadvantages
It is not considered that one is better than the other, as optimistic locks are used in less-than-write situations where collisions are really rare, which eliminates the overhead of locking and increases the overall throughput of the system. However, if there is frequent conflict, the upper application will continue to retry, which is to reduce the performance, so in this case, pessimistic locking is more appropriate. optimistic Lock Application

Use a self-growing integer to represent the data version number. The update checks whether the version number is consistent, such as the data version in the database is 6, update commits version=6+1, use the version value (=7) and the database Version+1 (=7) to compare, if equal, it can be updated, if not unequal, it is possible that other programs have updated the record. So the error is returned.

Implemented using timestamps.
Note: For both of these ways, hibernate comes with the implementation method: add annotation before using optimistic lock fields: @Version, Hibernate automatically validates the field on update. Pessimistic lock Application

You need to use a lock mechanism for the database, such as SQL Server's TABLOCKX (exclusive table Lock) When this option is selected, SQL Server will lock the entire table until the command or transaction ends. This prevents other processes from reading or modifying the data in the table.

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 is very large concurrency, pessimistic locking can cause a lot of performance problems, so we should choose optimistic locking method.
Pessimistic locks can result in long access to the database and poor concurrency, especially for long transactions.
Optimistic locking in the reality of the use of more, manufacturers more use. A typical pessimistic lock call that relies on a database:

SELECT * from account where name= ' Erica ' for update

This 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 is also a database-based lock mechanism implementation.

Note that locking is really done through the lock mechanism of the database only if the lock is set before the query starts (that is, before the hiberate generates SQL), otherwise the data has been loaded through a Select SQL that does not contain a FOR UPDATE clause, so the so-called database lock is not possible.

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 it comes with a lot of overhead for database performance, especially for long transactions, which are often unsustainable. Classic Case Study

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 locking, mostly based on the data version (versions) recording mechanism implementation. What is the 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 to be outdated 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 with a current value of 1;
The Current Account balance field (balance) is $ $.

1 operator A reads it out at this time (version=1) and deducts 50 (50 (100-$50) from its account balance.

2 during operator A's operation, operator B also reads this user information (version=1) and deducts 20 (20 (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 to the database (balance=$80), 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 "commit version must An optimistic lock policy that is larger than the current version of the record to perform an update, 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. Summary

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).

Below is reproduced other bloggers content "Hibernate pessimistic lock and optimistic lock " To do the collection: http://blog.csdn.net/fengxuezhiye/article/details/7380076

When it comes to pessimistic lock and optimistic lock, we should talk about the concurrency problem of database, the higher the isolation level of the database, the worse the concurrency .

key Content concurrency: After the current system has been serialized, you read the database, others can not query, called concurrency is not good

1. Pessimistic lock
With exclusive (I lock the current data, than people do not see this data), pessimistic lock is generally done by the database mechanism

Implementation of pessimistic Locks:

Usually relies on the database mechanism to lock the database during the refurbishment process, and no other user can read or modify

Application Scenarios for pessimistic locks:
Pessimistic lock is generally suitable for short things more (if a data is removed and added 1, immediately release)

Instance:

User 1, the user 2 read to the data at the same time, but the user 2 first-200, then the database is 800, now the user 1 also started-200, can user 1 just read the data is 1000, now the user with just a start reading the data 1000-200, and user 1 in the database in the update data is 800, it is logically said that user 1 should be 800-200=600, so that the update is lost. In this case, you can use two types of

Way to solve: pessimistic lock, optimistic lock.
Pessimistic Lock: User 1 read data, with the lock to read the data lock, then the user 2 is not read data, only the user 1 release lock user 2 can read, the same user 2 read data is also locked, so you can resolve the update is lost.

Entity class:

public class Inventory {
    private int itemno; 
    Private String ItemName;    
    private int quantity;
    public int Getitemno () {
        return itemno;
    }
    public void Setitemno (int itemno) {
        This.itemno = ItemNo;
    }
    Public String Getitemname () {
        return itemname;
    }
    public void Setitemname (String itemname) {
        this.itemname = itemname;
    }
    public int getquantity () {
        return quantity;
    }
    public void setquantity (int quantity) {
        this.quantity = quantity;
    }   
}

Map file:

 

Use of pessimistic locks:

If you want to use pessimistic locks, it must be locked when the data is loaded, usually with the FOR UPDATE statement

Hibernate uses load for pessimistic lock loading

Session.load (Class Arg (), Serializable Arg1,lockmode arg2) throws Hibernateexception

Lockmode: Pessimistic lock mode (general use of Lockmode.upgrade)

Session = Hibernateutils.getsession ();
            tx = Session.begintransaction ();
            Inventory INV = (Inventory) session.load (Inventory.class, 1, lockmode.upgrade);
            System.out.println (Inv.getitemname ());
            Inv.setquantity (Inv.getquantity () -200);

            Session.update (INV);
            Tx.commit ();

Lazy (lazy loading) is invalid if pessimistic lock is used

2. Optimistic lock
Optimistic lock: Is not a lock, is a conflict detection mechanism, optimistic locking concurrency is better, because I changed, others can casually modify the optimistic lock implementation: Commonly used is the version of the way (each table has a version of the field versions, a user update the database, version number +1, another user modified and then +1, when the user update discovers that the current version number of the database is inconsistent with the version number when reading the data, the database version number is equal to or less than the update.

Hibernate uses optimistic locks to be configured in the mapping file to take effect

Entity class

public class Inventory {
    private int itemno; 
    Private String ItemName;    
    private int quantity;   
    private int Version;//hibernate user to implement version optimistic locking, but need to configure public
    int Getitemno () {return ItemNo in the mapping file
        ;
    }
    public void Setitemno (int itemno) {
        This.itemno = ItemNo;
    }
    Public String Getitemname () {
        return itemname;
    }
    public void Setitemname (String itemname) {
        this.itemname = itemname;
    }
    public int getquantity () {
        return quantity;
    }
    public void setquantity (int quantity) {
        this.quantity = quantity;
    }
    public int getversion () {
        return version;
    }
    public void setversion (int version) {
        this.version = version;
    }
}

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.