Multi-thread pessimistic lock, optimistic lock, multi-thread

Source: Internet
Author: User

Multi-thread pessimistic lock, optimistic lock, multi-thread

1. pessimistic lock, as it is called, refers to a conservative attitude towards data being modified by the outside world (including other transactions of the current system, as well as transactions from the external system). Therefore, the data is locked during the entire data processing process. Pessimistic locks often rely on the locks provided by the database (and only the locks provided by the database layer can truly guarantee the exclusive data access; otherwise, even if the locking mechanism is implemented in the system, it cannot be ensured that the external system will not modify the data ).

Database lock mechanism:

1. uncommitted read (read uncommitted)

2. read committed)

3. repeatable read)

4. serializable)

Lock Mechanism:

Shared lock: other transactions can be read but cannot be modified.

Exclusive lock: other transactions cannot be read.

Lock granularity: generally divided into: Row lock, table lock, database lock

Explanation:

1. uncommitted read (read uncommitted)

When Transaction A of A updating database does not commit, another Transaction B is reading the update record of Transaction A, which may cause dirty reading. This is because Transaction A starts DB Transaction, when some DML operations are performed, the records are stored in the memory. At this time, transaction B reads the data committed by transaction A in the memory, resulting in dirty reads.

2. read committed)

Data modifications are read back only after commit. Opposite to 1.

3. repeatable read)

When the database isolation level is set to repeatable read, transaction B can modify the data read by A in the select statement of transaction A. When A executes the same SQL statement 2nd times, returns the same data as the previous one to eliminate repeated reads.

Note: I personally think that only after the isolation level is adopted for transaction A, the image of the database at the start time of the transaction is read, all operations after this time point will not affect the query in transaction A. It is based on the subsequent experiments in this article. If you have any questions, please note.

4. serializable)

When the database isolation level is set to Serializeable, the select statement in transaction A locks the data (in the data result set returned by the select statement ), the data cannot be modified (can be read). If transaction B performs an UPDATE operation on the data, it will be in the waiting state to eliminate Phantom reads.

Note: Transaction B can UPDATE the locked data in transaction A, which can be proved by subsequent experiments.

 

 

2. Compared with the pessimistic lock, the Optimistic lock mechanism adopts a more loose Locking mechanism. Pessimistic locks are implemented by the database lock mechanism in most cases to ensure maximum operation exclusiveness. However, there is a large amount of database performance overhead, especially for long transactions, which is often unbearable. The optimistic lock mechanism solves this problem to some extent. Optimistic locks are mostly implemented based on the data Version record mechanism. What is the data version? Add a version ID for the data. In the database table-based version solution, you can add a "version" field 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 version number is greater than the current version number of the database table, the data is updated, otherwise, expired data is considered.

 

 

Hibernate optimistic lock and pessimistic lock usage

Address: http://www.blogjava.net/baoyaer/articles/203445.html

Hibernate supports two lock mechanisms:
That is, the so-called Pessimistic Locking and OptimisticLocking )".

Pessimistic locks often rely on the locks provided by the database (and only the locks provided by the database layer can truly guarantee the exclusive data access; otherwise, even if the locking mechanism is implemented in the system, it cannot be ensured that the external system will not modify the data ).

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: the specific implementation of Oracle. Use the Oracle for update nowait clause to implement locking.

The pessimistic lock of Hibernate is also implemented based on the database lock mechanism. The following code locks query records:

1 String hqlStr = "from TUser as user where user. name = 'erica '";
2 Query query = session. createQuery (hqlStr );
3 query. setLockMode ("user", LockMode. UPGRADE); // lock
4 List userList = query. list (); // execute the query,

Obtain data query. setLockMode locks the record corresponding to the specific alias in the query statement (we have specified an alias "user" for the TUser class). In this case, all the returned user records are locked. Observe the SQL statements generated by Hibernate during runtime:

1 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 uses the for update clause of the database to implementPessimistic lockMechanism.

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: Only when the lock is set before the query starts (that is, before the Hiberate generates the SQL statement) Will the database lock mechanism be used for the lock process. Otherwise, data has been loaded through Select SQL that does not contain the for update clause. The so-called database locking is impossible.






Optimistic locks are mostly implemented based on the data Version record mechanism. What is the data version? Add a version ID for the data. In the database table-based version solution, you can add a "version" field 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 version number is greater than the current version number of the database table, it is updated, otherwise, expired data is considered.

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>

 

Add a Version attribute Descriptor
Code content

1 2 <class
3 name = "org. hibernate. sample. TUser"
4 table = "t_user"
5 dynamic-update = "true"
6 dynamic-insert = "true"
7 optimistic-lock = "version"
8>
9 <id
10 name = "id"
11 column = "id"
12 type = "java. lang. Integer"
13>
14 <generator class = "native">
15 </generator>
16 </id>
17 <version
18 column = "version"
19 name = "version"
20 type = "java. lang. Integer"
21/>
22 ......
23 </class>
24 25


 

 

Note that the version node must appear after the ID node.
Here, we declare a version attribute to store the user's version information and store it in the version field of the TUser table. At this point, if we try to write a piece of code to update the record data in the TUser table, such:
Code content

1 Criteria criteria = session. createCriteria (TUser. class );
2 criteria. add (Expression. eq ("name", "Erica "));
3 List userList = criteria. list ();
4 TUser user = (TUser) userList. get (0 );
5 Transaction tx = session. beginTransaction ();
6 user. setUserType (1); // update the UserType Field
7 tx. commit ();
8

 

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 and operate on the user named Erica to simulate concurrent updates:
Code content

1 Session session = getSession ();
2 Criteria criteria = session. createCriteria (TUser. class );
3 criteria. add (Expression. eq ("name", "Erica "));
4 Session session2 = getSession ();
5 Criteria criteria2 = session2.createCriteria (TUser. class );
6 criteria2.add (Expression. eq ("name", "Erica "));
7 List userList = criteria. list ();
8 List userList2 = criteria2.list (); TUser user = (TUser) userList. get (0 );
9 TUser user2 = (TUser) userList2.get (0 );
10 Transaction tx = session. beginTransaction ();
11 Transaction tx2 = session2.beginTransaction ();
12 user2.setUserType (99 );
13 tx2.commit ();
14 user. setUserType (1 );
15 tx. commit ();
16

Run the preceding code and the code will be thrown at tx. commit ().StaleObjectStateExceptionException, and pointed out that the version check failed, the current transaction is trying to submit an expired data. By capturing this exception, we can handle it when optimistic lock validation fails.




Comparison between pessimistic locks and optimistic locks:
Pessimistic locks are implemented by the database lock mechanism in most cases to ensure maximum operation exclusiveness. However, there is a large amount of database performance overhead, especially for long transactions, which is often unbearable;
Compared with pessimistic locks, optimistic locks adopt a more loose locking mechanism. The Optimistic Locking Mechanism is often based on the data storage logic in the system, so it also has certain limitations. For example, in the above example, The Optimistic Locking mechanism is implemented in our system, update operations from external systems are 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 (for example, implementing Optimistic Locking policies in the database storage process, only the data update path based on this stored procedure is open to the outside, rather than the database table is open to the outside ).
Hibernate has built-in optimistic lock implementation in its data access engine. If you do not need to consider the update operations of the external system on the database, using the transparent optimistic lock provided by Hibernate will greatly improve our productivity.
In Hibernate, the optimistic-lock attribute of the class descriptor can be used together with the version descriptor.
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 officially recommended by Hibernate. It is also the only lock mechanism in Hibernate that is still effective when the data object is modified from the Session. Therefore, we generally choose the version method as the Hibernate optimistic lock implementation mechanism.

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.