Application scenarios and scenarios of optimistic locks and pessimistic locks

Source: Internet
Author: User

Application scenarios and scenarios of optimistic locks and pessimistic locks

 

Locking)
During the implementation of business logic, data access needs to be exclusive. For example, end computing on the day of the Financial System
Processing, we want to process the data at a cut-off time point, rather than in the settlement process.
(Several seconds or several hours), and the data changes again. In this case, we need to use some machines
This mechanism ensures that the data is not modified by the outside world during an operation.
Lock, that is, lock the target data we have selected so that it cannot be modified by other programs.
Hibernate supports two lock mechanisms: Pessimistic Locking )"
And "Optimistic Locking )".


Pessimistic Locking)
Pessimistic lock, just like its name, refers to external data (including other current transactions of the system, as well
The transaction processing of the external system.
Status. Pessimistic locks are implemented based on the locks provided by the database (and only the locks provided by the database layer can be implemented.
Data access is exclusive. Otherwise, even if the lock mechanism is implemented in the system, external systems cannot be guaranteed.
Does not modify data ).
A typical pessimistic lock call that relies on databases:
Select * from account where name = "Erica" for update
This SQL statement locks all records that meet the search criteria (name = "Erica") in the account table.
Before the transaction is committed (the lock in the transaction process will be released when the transaction is committed), these records cannot be modified by the outside world.
The pessimistic lock of Hibernate is also implemented based on the database lock mechanism.
The following code locks query records:

 

String hqlStr =
"From TUser as user where user. name = 'erica '";
Query query = session. createQuery (hqlStr );
Query. setLockMode ("user", LockMode. UPGRADE); // lock
List userList = query. list (); // execute the query to obtain data.
Query. setLockMode: locks the records corresponding to a specific alias in the query statement.
The TUser class specifies an alias "user"). Here, all user records returned are locked.
Observe the SQL statements generated by Hibernate during runtime:
Select tuser0 _. id as id, tuser0 _. name as name, tuser0 _. group_id
As group_id, tuser0 _. user_type as user_type, tuser0 _. sex as sex
From t_user tuser0 _ where (tuser0 _. name = 'erica ') for update
Here, Hibernate implements the pessimistic lock mechanism by using the for update clause of the database.
The locking modes of Hibernate include:
Ø LockMode. NONE: No lock mechanism.
Ø LockMode. WRITE: Hibernate will automatically Insert and Update records
.
Ø LockMode. READ: Hibernate will automatically obtain the data when reading the record.
The above three lock mechanisms are generally used internally by Hibernate, for example, to ensure Update
During the process, the object will not be modified by the outside world, and the WRITE lock will be automatically added to the target object in the implementation of the save method.
Ø LockMode. UPGRADE: locks the database by using the for update clause.
Ø LockMode. UPGRADE_NOWAIT: specific implementation of Oracle, using the Oracle
Update nowait clause implements locking.
The above two locking mechanisms are commonly used at the application layer. The locking is generally implemented through the following methods:
Criteria. setLockMode
Query. setLockMode
Session. lock
Note that the lock is set only before the query starts (that is, before the Hiberate generates the SQL statement ).
The database lock mechanism is used to lock the data. Otherwise, the data has passed for update
When the Select SQL statement of the clause is loaded, the so-called database locking is impossible.

 

 


Optimistic Locking)
Compared with pessimistic locks, optimistic locks adopt a more loose locking mechanism. Pessimistic lock
It is implemented by the database lock mechanism to ensure maximum operation exclusivity. But the following comes the database.
Performance overhead, especially for long transactions, is often unbearable.
For example, in a financial system, when an operator reads user data and reads user data
When the row is modified (such as changing the user account balance), if the pessimistic lock mechanism is used, it means that the entire operation has passed
Process (the entire process from the operator reading data, starting to modify until the Modification result is submitted, and even operations
The database record is always locked. You can imagine how long it takes

Hundreds of thousands of concurrent jobs.
The Optimistic Locking Mechanism solves this problem to some extent. Optimistic lock, mostly based on data versions
(Version) record mechanism implementation. What is the data version? Add a version ID for the data.
In the database table version solution, a "version" field is added to the database table.
.
When reading the data, read the version number together, and then add one to the version number when updating the data. In this case
The version data of the submitted data is compared with the current version information recorded in the database table. If the submitted data
If the version number is greater than the current version number of the database table, it is updated. Otherwise, it is considered as expired data.
For the example of modifying user account information above, assume that there is
The version field. The current value is 1, and the current account balance field (balance) is $100.
1 operator A reads it (version = 1) and deducts $50 from its account balance.
($100-$50 ).
2. During operator A's operations, operator B also reads this user information (version = 1) and
Deduct $20 ($100-$20) from your account balance ).
3. Operator A completes the modification and adds the data version number (version = 2) together with the account
Balance after Division (balance = $50), submit to database update, because the submitted data version is large
The current version is recorded in the database, the data is updated, and the version of the database record is updated to 2.
4 operator B completes the operation, and also adds version 1 (version = 2) to try to submit data to the database
According to (balance = $80), but when comparing the database version, it is found that operator B Submitted
The data version number is 2, and the current database record version is 2, which does not meet the requirement that "the submitted version must be greater than the record
The optimistic lock policy of update is executed only after the current version is recorded. Therefore, the submission of operator B is rejected.
In this way, operator B is prevented from overwriting the operation with the modification result of the old data based on version = 1.
Possible result of Employee A's operation.
The above example shows that the Optimistic Locking mechanism avoids the database lock overhead in long transactions (operator
The database data is not locked during operator B operations), which greatly improves the system
Overall performance.
It should be noted that the optimistic lock mechanism is often based on the data storage logic in the system, so it also has a certain
Limitation, as in the above example, because the optimistic lock mechanism is implemented in our system, users from external systems
The balance update operation is not controlled by our system, so dirty data may be updated to the database. In
In the system design phase, we should fully consider the possibility of such situations and make corresponding adjustments (such
The optimistic lock policy is implemented in the database stored procedure, and only the data update path based on the stored procedure is opened to the outside world.
Path, instead of making the database table public ).
Hibernate has built-in optimistic lock implementation in its data access engine. If you do not need to consider the external system logarithm
The update operation of the data library is implemented using the transparent optimistic lock provided by Hibernate, which will greatly improve our
Productivity.
In Hibernate, you can combine the optimistic-lock attribute of the class descriptor with the version
Descriptor.
Now, we add an optimistic lock mechanism to the TUser in the previous example.

1. First, add the optimistic-lock attribute for the TUser class descriptor:
<Hibernate-mapping>
<Class
Name = "org. hibernate. sample. TUser"
Table = "t_user"
Dynamic-update = "true"
Dynamic-insert = "true"
Optimistic-lock = "version"
>
......
</Class>
</Hibernate-mapping>
The optimistic-lock attribute has the following optional values:
Ø none
No optimistic lock
Ø version
Optimistic Locking through version Mechanism
Ø dirty
Optimistic lock by checking changed attributes
Ø all
Optimistic lock by checking all attributes
The optimistic Lock Mechanism Implemented by version is the optimistic lock implementation officially recommended by Hibernate.
It is the only lock that is valid when the data object is modified out of the Session.
. Therefore, we generally choose the version method as the Hibernate optimistic lock implementation mechanism.
2. Add a Version attribute descriptor.
<Hibernate-mapping>
<Class
Name = "org. hibernate. sample. TUser"
Table = "t_user"
Dynamic-update = "true"
Dynamic-insert = "true"
Optimistic-lock = "version"
>
<Id
Name = "id"
Column = "id"
Type = "java. lang. Integer"
>
<Generator class = "native">

</Generator>
</Id>
<Version
Column = "version"
Name = "version"
Type = "java. lang. Integer"
/>
......
</Class>
</Hibernate-mapping>
Note that the version node must appear after the ID node.
Here we declare a version attribute to store the user's version information, which is stored in the TUser table
In the version field.
At this point, if we try to write a piece of code to update the record data in the TUser table, such:
Criteria criteria = session. createCriteria (TUser. class );
Criteria. add (Expression. eq ("name", "Erica "));
List userList = criteria. list ();
TUser user = (TUser) userList. get (0 );
Transaction tx = session. beginTransaction ();
User. setUserType (1); // update the UserType Field
Tx. commit ();
Every time we update the TUser, we can find that the version in the database is increasing progressively.
If we try to start another Session before tx. commit
User to simulate concurrent updates:
Session session = getSession ();
Criteria criteria = session. createCriteria (TUser. class );
Criteria. add (Expression. eq ("name", "Erica "));
Session session2 = getSession ();
Criteria criteria2 = session2.createCriteria (TUser. class );
Criteria2.add (Expression. eq ("name", "Erica "));
List userList = criteria. list ();
List userList2 = criteria2.list (); TUser user = (TUser) userList. get (0 );
TUser user2 = (TUser) userList2.get (0 );
Transaction tx = session. beginTransaction ();
Transaction tx2 = session2.beginTransaction ();
User2.setUserType (99 );
Tx2.commit ();
User. setUserType (1 );
Tx. commit ();
Run the preceding Code. The Code will throw StaleObjectStateException at tx. commit ().
And indicates that the version check fails. The current transaction is trying to commit an expired data. By capturing this exception, I
When optimistic lock validation fails

 

 

 

Related Article

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.