《《《《《《《《《《《《《《《《《《《《《《《《《
Pessimistic lock (Pessimistic lock):
As the name suggests, is very pessimistic, every time to get (take) the data are thought that others will be modified, so each time to take (fetch) data will be locked, so that people want to take this data will block (blocking) until it gets the lock. The traditional relational database inside the use of a lot of this locking mechanism, such as row locks, table locks, read locks, write locks, etc., are locked before doing the operation.
Optimistic lock (Optimistic lock):
As the name suggests, is very optimistic, every time to get (take) the data are thought that others will not be modified, so will not be locked, but in the update will be judged in the meantime if someone else to update this data, you can use the version number and other mechanisms.
Optimistic locks are suitable for multiple-read application types, which can increase throughput, as if the database provides optimistic locks that are provided similar to the write_condition mechanism.
Both types of locks have advantages and disadvantages, do not think one is better than the other, such as optimistic lock for the case of less write, that is, conflicts really rarely occur, this can save the lock overhead, increase the overall throughput of the system. However, if there is a constant conflict, the top application will continue to retry (try again, and then apply), so as to reduce performance, so this situation with pessimistic lock is more appropriate.
Original: http://blog.csdn.net/hongchangfirst/article/details/26004335
Author: Hongchangfirst
Hongchangfirst's homepage: http://blog.csdn.net/hongchangfirst
the "" "" "" "" "" "" "" "
Why you need a lock (concurrency control).
In a multiuser environment, multiple users may update the same record at the same time, which creates a conflict. This is the famous concurrency problem.
Typical conflicts are:
L Lost Update: The update of one transaction overrides 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.
L Dirty read: Dirty reads occur when a transaction reads another record that completes half of the transaction. For example: The user a,b sees the value is 6, the user B changes the value 2, the user a reads the value still is 6.
In order to solve the problems caused by these concurrency. We need to introduce concurrency control mechanisms. concurrency control mechanism
Pessimistic lock: It is assumed that concurrent conflicts will occur, shielding all operations that may violate data integrity. [1]
Optimistic lock: Assuming no concurrent conflicts occur, check for data integrity violations only when committing operations. [1] The optimistic lock does not solve the problem of dirty reading. optimistic Lock Application
1. Use a self growing integer to represent the data version number. Update to check the consistency of the version number, such as the data version in the database is 6, update the submission version=6+1, use the version value (=7) and the database Version+1 (=7) as compared, if equal, you can update, if it is not possible other programs have updated the record, So it returns an error.
2. Use time stamp to achieve.
Note: For both of these ways, Hibernate is implemented by: before adding annotation to the field using the optimistic lock: @Version, Hibernate automatically validates the field when it is updated.
= = = "
Optimistic locking is a strategy that we often take in the same database transaction because it enables our system to maintain high performance and improve concurrency access control. Optimistic lock, as the name implies is to maintain an optimistic attitude, we believe that the system of concurrent updates of the transaction will not be very frequent, even if the conflict is nothing, big deal again. The basic idea is that every time we submit a transaction update, we want to see if the things we want to modify have not been modified by other transactions since the last read, and the update will fail if modified. Because optimistic locks don't actually lock any records, therefore, the transaction isolation level of the database is set to read committed or lower isolation boundaries, so it is not possible to avoid the problem of non-duplication (since read transactions do not block other transactions at this time), so when optimistic locking, the system should allow the emergence of the problem of non-duplication.
There are generally three ways to do this: Version field: Add a Version control field to our entity and add the value of the version field to 1 each time the transaction is updated. Timestamp (timestamps): When this strategy is taken, the current time of the system is compared with the time when the entity was loaded each time the update is to be submitted, and if it is inconsistent, the optimistic lock fails, which rolls back the transaction or attempts to commit again. There are some deficiencies in the use of timestamps, for example, in a clustered environment, the time synchronization of each node may be problematic, and if the concurrent transaction interval is less than the minimum clock unit of the current platform, then the problem of overwriting the previous transaction result occurs. Therefore, the general use of version of the field is better. Based on all the properties of the detection: This strategy, you need to compare each field after reading has not been modified, so this strategy to achieve a more cumbersome, requiring a comparison of each property, if the use of hiernate, because hibernate in the first level of cache can be dirty detection, You can then determine which fields have been modified to dynamically generate SQL statements for updates.
Pessimistic lock Application
Need to use the lock mechanism of the database, such as SQL Server TABLOCKX (exclusive table Lock) When this option is selected, SQL Server locks up the entire table until the command or transaction ends. This prevents other processes from reading or modifying data in the table.
Used in SQL Server
Begin Tran
Select top 1 @TrainNo =t_no
From Train_ticket with (UPDLOCK) where s_flag=0
Update Train_ticket
Set T_name=user,
T_time=getdate (),
S_flag=1
where t_no= @TrainNo
Commit
We used the WITH (UPDLOCK) option in the query, and we added an update lock to the record when we queried the record, indicating that we were about to update the record. Note that update locks and shared locks are not conflicting, that is, other users can also query the contents of this table, but the update lock and exclusive lock are conflicting. So the other update users will block. Conclusion:
In the actual production environment, if the concurrent volume is not large and do not allow dirty read, you can use pessimistic lock to solve the concurrency problem, but if the system concurrency is very large, pessimistic locking will bring a very large performance problems, so we have to choose optimistic locking method.
《《《《《《《《《《《《《《《《《《
Lock (Locking)
In the process of implementing business logic, it is often necessary to ensure the exclusivity of data access. such as in the financial system of the day-end settlement
In processing, we want to deal with data at a cut-off point in time, rather than in the process of closing
(It could be a few seconds, maybe a few hours), and the data will change again. At this point, we need to go through some machines
System to ensure that the data in a certain operation will not be modified by the outside, such a mechanism, here is the so-called
"Lock", which locks our selected target data so that it cannot be modified by another program.
Hibernate supports two locking mechanisms: the usual "pessimistic lock (pessimistic locking)"
and "optimistic lock (optimistic locking)".
Pessimistic lock (pessimistic locking)
A pessimistic lock, as its name implies, is about the data being externally (including other current transactions of the system, as well as from
The transaction processing of the external system is conservative, so the data is locked during the whole process of processing
State. The implementation of pessimistic locks often relies on the lock mechanism provided by the database (and only the lock mechanism provided by the database layer can
Truly guarantee the exclusivity of data access, otherwise, even in this system to achieve the locking mechanism, can not guarantee the external department
Data is not modified by the EC).
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 until this transaction is committed (the locks in the transaction are released when the transaction is committed).
Hibernate's pessimistic lock is also based on the database lock mechanism implementation.
Note that locking is only set before the query starts (that is, before hiberate generates SQL)
Locks are actually handled through the lock mechanism of the database, otherwise the data has passed without a for update
clause is loaded in the Select SQL, so the so-called database lock is not discussed.
Optimistic lock (optimistic locking)
In the case of pessimistic locks, the optimistic locking mechanism adopts a more relaxed locking mechanism. Pessimistic lock in most cases depending on
Rely on the database lock mechanism to achieve the maximum degree of exclusive operation. But then there's the database.
The overhead of performance, especially for a long transaction, is often unbearable.
such as a financial system, when an operator reads the user's data and reads the user data on the basis of the progressive
When a row is modified (such as changing the user account balance), if the pessimistic lock mechanism is used, it means that the entire operation
Thread (read the data from the operator, start the modification until the whole process of submitting the modification results, even including the operation
The time that the member goes to make coffee, the database record is always in the lock state, can imagine, if face a few
Hundreds of thousands of concurrent, such a situation will lead to what kind of consequences.
The optimistic locking mechanism solves this problem to some extent. Optimistic locks, mostly based on data versions
(Version) Recording mechanism implementation. What is the data version. Adds a version identifier for the data, which is based on the
In the version solution of a database table, you typically add a "version" field to the database table to
Realize.
When you read out the data, read the version number together, and then when you update it, add one to this version number. At this time, will mention
The version data of the data is compared with the current version information of the corresponding record 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 an expired data.
For the above example of modifying user account information, assume that the account information table in the database has a
Version field, the current value is 1, and the Current Account balance field (balance) is $.
1 operator A at this time read it out (Version=1) and deduct $ from its account balance
($100-$50).
2 during operator a operation, operator B also reads this user information (version=1), and
Deduct $ ($100-$20) from its account balance.
3 operator a completed the modification work, the data version number plus one (version=2), together with the account buckle
In addition to the balance (balance=$50), submit to the database update, at this time due to the submission of data version of the large
To the current version of the database record, the data is updated, and the database record version is updated to 2.
4 operator B completes the operation, and the version number plus one (version=2) attempts to submit the number to the database
According to (BALANCE=$80), but at this time compared to the record version of the database found that operator B submitted the
The data version number is 2 and the current version of the database record is 2, not satisfied "the submit version must be greater than the recorded
Recording the current version to perform an optimistic lock policy for update, so operator B's submission was dismissed.
This prevents operator B from overwriting the operation with the results of the old data modification based on Version=1
The operation result of the member A May.
As can be seen from the example above, the optimistic locking mechanism avoids the locking overhead of a database in a long transaction (operator A
And operator B in the process, there is no database data lock, greatly increased the large concurrent volume of the system
Overall performance of the EC.
It should be noted that the optimistic locking mechanism is often based on the data storage logic in the system, so there is a certain bureau
Limits, as in the above example, because the optimistic locking mechanism is implemented in our system, the user from the external system
The balance update operation is not controlled by our system and may result in dirty data being updated to the database. In
In the system design phase, we should take full account of the possibility of these situations and adjust accordingly (e.g.
Implement optimistic lock policy in database stored procedure, only Open Data update path based on this stored procedure externally
path, rather than exposing the database table directly to the outside.
《《《《《《《《《《《《《《《《《《《《《《《《