Summary optimistic and pessimistic locking

Optimistic and pessimistic locking is used when the operation of the database, update locks are optimistic beginning, pessimistic locking query record the moment, ending both commit or rollback

Pessimistic locks, lock up, not change the optimistic lock only judge when others have not updated it to turn over the data, to ensure the goods are sold only once, you can use the version number of mechanisms, can improve data throughput

 Concurrency control mechanism, when a user locks the data, other users can not access

 

Pessimistic locking (Pessimistic Lock), by definition, is very pessimistic, pick up data every time think others will modify, so every time she took the data will be locked, so people want to take this data will block until it takes to lock. Traditional relational database inside to use a lot of this locking mechanism, such as row locks, table locks, etc., read lock, write lock, are locked before doing the first operation.

 

Optimistic locking (Optimistic Lock), by definition, is very optimistic, pick up data every time that others are not modified, so it will not be locked, but when the update will determine what others during this time did not go to update this data, you can use the mechanisms of the version number. Optimistic locking is suitable for the types of applications to read, so you can improve throughput if the database provided similar write_condition optimistic locking mechanisms are actually provided like.

 

Other kinds of locks have advantages and disadvantages, can not be considered to be a good alternative, as optimistic locking apply to lower write relatively few cases, namely when the conflict is really rare, so can save a lock of overhead, plus large throughput of the entire system. However, if the frequent conflict, the upper application will continue to be retry, such but rather reduces the performance, so use pessimistic locking is more appropriate in this case.

 

1, select either pessimistic locking strategy, or optimistic locking strategy. If an object is on the lock, then the object will be under the control and influence of the lock. If the lock is an exclusive lock, then other sessions can not modify it.

 

2. Select the pessimistic locking strategy, or optimistic locking strategy, mainly by the application and business requirements determined. If your application and business often appear from what I see the value you want to modify records, to complete the record I modified this period of time, there is a greater probability that the record was modified by another session. In other words, when I actually go to make changes, this value is likely to have been recorded and I had seen different. Well then, take the pessimistic locking strategy, perhaps better. Take a pessimistic locking strategies typical operation is select ... for undate. Through this operation, so that from the beginning I see from this record, this record is the exclusive lock on, then the record does not allow other sessions any changes.

 

In contrast, if your business applications and very seldom occurs this scenario, then select the optimistic locking strategy might work better.

 

3, the core strategy is actually two different starting and ending points of time holding the lock, the lock is pessimistic reading recorded from the moment it began, but only starting UPDATE optimistic locking moment; both end points are Like, are issued commit or rollback command. Therefore, the duration pessimistic locking strategy will lock longer, while the duration is shorter optimistic locking. Its impact is concurrency. Concurrency pessimistic locking is less than optimistic locking.

 

4, no matter which strategy is adopted, should ensure data integrity. Therefore, when using optimistic locking strategy is likely incomplete data. For example: A depositor deposits of $ 100, assuming that at almost the same time, there were two pen business, business into a 1 for 50, the other its online shopping business is 30 yuan. Obviously, after these two operations, A's deposit balance should be $ 120 (100 + 50-30). But we imagine at the database level, it may happen that, when deposited in the bank counter 50, the bank operator received 50 yuan in cash A deposit, and through select statement to see the current balance of 100 A meta (command which is issued by the following statement:

 

select Balance

 

   from deposit balances

 

= depositors A depositor account number where the bank account;)

 

And then, issues a command

 

update deposit balances

 

      set balance = 150

 

    = depositors A depositor account number where the bank account number;

 

But it sees A balance of $ 100, to revise its balance of 150 A this period, A in consumer behavior online trading system has led to the A's balance to $ 70 (100-30) and submitted in a. When an instruction issued by the bank employees also submitted A balance into a 150 yuan, the equivalent of armor online consumer behavior did not produce any charges. This is obviously not true, but to avoid arise.

 

If the system uses a pessimistic locking strategy, then view the current balance of armor from a bank employee that moment onwards (instruction then the query would be:

 

select Balance

 

   from deposit balances

 

= depositors A depositor account number where the bank account for update;)

 

The record has been locked, then the armor of online consumer behavior resulting from the trading system deducted from A's account will be operating in a wait state. Until the bank employees submitted the relevant directive, the trading system in order to deduct armor of money. In this way, we can ensure that A's account balance is correct.

 

The strategy is clearly pessimistic locking can guarantee the correctness and completeness of the business. But then imagine if the armor in deposits, bank employees urgency, or depositors A said wait a minute, I have to consider whether to save some more. Then, the operation of bank employees will not submit, then online trading system on the A-debit the account would have been in a wait state, or wait a certain time, suggesting a return to the failed charge. This efficiency and customer systems, it is not a good experience.

 

5, considering that this problem pessimistic locking strategy can produce, so we designed the application, you can take some other ways to avoid this from happening. The idea is that in a real submission, confirm that you want to modify the data has not changed too. The main methods are as follows:

 

(1), into the updated original data.

 

     update deposit balances

 

      set balance = 150

 

    = depositors A depositor account number where the bank account number and balance = 100;

 

(2) increase the modified time stamp on the recording (ora_rowscn pseudo column can also be used). That is, at the start of the transaction to acquire the timestamp of the record, when modified, check the timestamp, if the agreement is modified.

 

6, in fact, the example I cited above, if the business design, select the update instructions

 

update deposit balances

 

      Balance Balance set = + 50

 

    = depositors A depositor account number where the bank account number;

 

So, even in the case of optimistic locking strategy can still guarantee the correctness and completeness of the data.

 

 

 

Why lock (concurrency control)?

In a multiuser environment, at the same time may have multiple users update the same record, which will conflict. This is known as concurrency issues.

Typical conflict:

l lost update: update of a transaction covered by the updated results of other transactions, the so-called lost updates. For example: the value of the user A from 2 to 6, the user B from the value 2 to 6, A user lost his updates.

l Dirty read: when a transaction is completed reading the other half of the transaction record, dirty read occurs. Example: User A, 6 B values ​​are seen, the B value to the user 2, the user A read value is still 6.

In order to solve the problems caused by these concurrency. We need to introduce concurrency control mechanism.

Concurrency control mechanism

    The most common approach to multi-user concurrent access is locked. When a user locks an object in the database, other users can no longer access the object. The impact of concurrent access lock reflected in the lock granularity. For example, put a lock on the table limit concurrent access to the entire table; lock on the data page limit on access to the entire data page; lock on the line only limit on concurrent access to the row. Visible lock granularity minimum row, concurrent access to the best, maximum page lock granularity, the lock table between two persons.

 

Pessimistic locking: assume concurrency violation occurs, the shield may be in violation of all operational data integrity. [1] pessimistic locking assume other users attempt to access or change you are visiting, the probability of objects that change is very high, so the pessimistic locking environment, it is the object lock before you begin to change this object, and until only release the lock after you submit the changes. Pessimistic flaw is whether page locks or row locks, lock time can be very long, so long may restrict access of other users, that is to say pessimistic locking concurrent access is not good.

Optimistic locking: Suppose concurrency conflicts do not occur, only checks data integrity violation when a commit operation. [1] optimistic lock can not solve the problem of dirty read. Optimistic locking believes that the probability of another user attempts to change the subject you are to change is very small, so the optimistic lock until you are ready to commit the change when the object is locked, when you read and change the object does not lock . Visible optimistic than pessimistic locking lock time is short locks, optimistic locks can be locked with a larger size to obtain better performance concurrent access. But if a second reading before the user just submitted changes in the first user of the object, then when he finished when commit your changes, the database will find that the object has changed, so that the second user may not do not re-read the object and make changes. This shows that optimistic locking environment could increase the number of concurrent users to read the object.

 

     From the database vendor's point of view, the use of optimistic locking page is relatively good, especially in batch operations affect many rows can put less of locks, reducing the need for resources to improve the performance of the database. Then consider the clustered index. Records in the database are aggregated according to the physical order of the index stored. If you use page locks, when two users simultaneously access change at the adjacent two rows on the same data page, which a user must wait for another user to release the lock, which will significantly reduce system performance. Like most relational databases and interbase, using the optimistic locking, and is shared read lock, write lock is exclusive. It can then be placed in a locked read read lock, but could not place a write lock; you can not write lock in place any longer locks. Lock is an effective means to resolve the current multi-user concurrent access.  

Optimistic locking applications

1. Since the growth of the integer data version number. Checking for updates to version numbers are the same, such as data in the database version 6, submit the updated version = 6 + 1, database version + 1 (= 7) compared using the version value (= 7) and, if they are equal, it is possible update, if it is possible to vary other programs that record has been updated, so returns an error.

2. Use timestamps to achieve.

Note: For the above two methods, Hibernate own implementations: the optimistic locking field before adding annotation: @Version, Hibernate automatic calibration when updating the field.

Pessimistic locking application

You need to use the locking mechanism of the database, such as SQL SERVER of TABLOCKX (exclusive table lock) When this option is selected, SQL Server will set an exclusive lock until the end of the order or transaction on the entire table. This will prevent other processes to read or modify data in the table.

SqlServer use

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 use the query time with (UPDLOCK) option in the query log to record when we add an update lock, this means that we will soon record to be updated. Note that update locks and shared locks are not in conflict, that is, other users can also query the contents of this table, however, and update locks and exclusive locks are in conflict, so other users will be updated obstruction.

in conclusion

In the actual production environment inside, if concurrency is not and does not allow dirty reads, you can use pessimistic locking to solve concurrency problems; but if the system is very large concurrent case, pessimistic locking will bring very large performance problem, so we have to choose optimistic locking methods.

 

 

https://www.cnblogs.com/jinlinFighting/p/5933724.html

Guess you like

Origin www.cnblogs.com/suger43894/p/11024102.html