JAVA written interview of optimistic locking and pessimistic locking

I. Introduction

  When school recruit, whether written or interview, I have met optimistic and pessimistic locking lock problem, then hurry back just a bit two of their concept, and not get to the bottom, and now will begin his spare time is hard to look back on the past of candidates knowledge point charge, simply to increase knowledge and research that feeling surprisingly good, oh.

So back to the subject, optimistic and pessimistic locking lock, I will combine see and explain the scenario, the application pick the time of choosing good examples to help you understand the savings and give their own thinking.

Second, the text

Pessimistic lock: As the name implies, it refers to the data to be conservative about the outside world (including other current affairs of the systems, and transaction processing from external systems) changes, therefore, the entire data processing, the data in (human) locked state. Before the operation front end of the transaction, then the transaction can only wait.

PS We're probably familiar with the keyword sycchronized, is a pessimistic lock on the system to achieve, but I saw some bloggers that " only lock mechanism provided by the database layer in order to truly ensure exclusive access to the data, otherwise, even if to achieve a locking mechanism in this system, there is no guarantee the external system does not modify the data ", pending further research.

So what is the underlying database lock mechanism to provide it? The usual mysql InnoDB storage engine example (Bowen cited the following section links https://blog.csdn.net/zxx901221/article/details/83239771 ):

  Join merchandise table items table has a field status, status = 1 indicates that the product is not an order, status = 2 indicates that the product has been under a single, then we must ensure that the status of this product before orders for each item = 1 . Suppose a commodity, its id 10000; If no lock, then the operation is as follows:

  // isolated product status
       SELECT Status items from WHERE ID = 10000;
       // The line merchandise information generation
       INSERT INTO Orders (ID, item_id) values (null, 10000);
       // modified product state 2
       Update the Items SET Status = 2 where id = 10000;

       The above scenario possible problems in highly concurrent environments:

       As already mentioned only the status of goods = 1 it is to be under a single operation, the above first operation, check out the commodity status of 1. But when we execute the third step of the update operation, there may be other people the first step towards a single modification of status under Item 2 of merchandise, but we do not know that the data has been modified, so you can

It can cause the same to be a single secondary product, such that the data is inconsistent. So in this way it is unsafe.

    Use pessimistic locking is achieved: In the above scenario, the product information from the query out to modify the middle of a process order handling, use pessimistic locking principle is that, when we check out the items of information to put the current data is locked, until we change would then be unlocked. Well, in this process, because the items are locked up, there would not be a third

It was to be modified.

        Note: To use pessimistic locking, we have to turn off auto-commit property mysql database because MySQL default autocommit mode, that is, when you perform an update, MySQL will immediately submit the results. We can use the command to set the MySQL a non-autocommit mode:

  set autocommit = 0;
       After setting the autocommit, we can perform our normal business up. As follows:
       // begin a transaction
       begin; / begin work; / start transaction; ( you can choose one of the three)
       // check out the product information
       the SELECT Status items from the WHERE Update for the above mentioned id = 10000;
       // generate orders based on product information
       insert the Orders iNTO (the above mentioned id, item_id) values (null, 10000);
       // modify commodity status as 2
       Update items the SET status = 2 the WHERE the above mentioned id = 10000;
       // commit the transaction
       commit; / commit work;

       The above begin / commit to the transaction start and end, as in the previous step we closed autocommit mysql, so the need to manually control the transaction commits. And with common query is not the same, we use the select ... for update of the way, so that through the database to achieve a pessimistic locking.

  Also note that, in a transaction, only the " SELECT ... the FOR UPDATE time" with the sum of other data will wait until after the end of transaction execution, SELECT ... generally not affected by this influence. Take the above example, when I execute the select status from items where id = 10000 for update; after. If I run again in another transaction

select status from items where id = 10000 for update; the second transaction will wait until the first transaction commits, this time the second query in a blocked state, but if I were to perform select status in the second transaction from items where id = 10000; the normal check out the data, is not affected by the first transaction.

  Text also mentioned LOCK IN SHARE MODE and lock level, I do not really understand the cut, friends who are interested can see the original.

  Optimistic locking: relatively pessimistic locking, the optimistic assumption that the lock will not cause data conflict under normal circumstances, so be updated in time to submit the data before formal conflict or not the data to detect a conflict if found, then let user error message is returned, allowing users to decide what to do.

  Achieve optimistic locking generally have the following two ways:

       1. Use the data version (Version) recording mechanism to achieve, which is the most common kind of optimistic locking implementation. What version of the data? That is, a version identifier of data increases, is generally achieved by adding a digital type of database table "version" field. When reading data, the version value of the field is read out with the data updated every time, which

version value of +1. When we submit updated information to determine the current version of the database table with the first taken out of the version corresponding to the value recorded for comparison, if the current version of the database table version number equal to the value of the first taken out, then be updated, otherwise considered stale data.

       2. The optimistic locking the first and second implementation is almost the same in the required optimistic locking control table to add a field name does not matter, the field type using a time stamp (timestamp), a version similar to the above, also in the check the update time of filing of the current time stamp data in the database and update themselves before taking to the timestamp comparison,

If the agreement is OK, otherwise version conflicts.

  Or take the example of previous commodity table items table has a field status, status = 1 indicates that the product is not an order, status = 2 indicates that the product has been under a single, then we must make sure this product before orders for each item the status = 1. Suppose a commodity, its id 10000;

       3 comprises a single step of operation:

       // check out the product information

       select (status,version) from items where id=#{id}

       // generate orders based on product information

  ---------------------------------

       // modify commodity status of 2

       update items set status=2,version=version+1 where id=#{id} and version=#{version};

  Such a system has value "1", A and B now have to take the same time to the client this value. A and B after the client wants to change this value, it is assumed to be changed to A 12, B 13 to change, if not controlled, regardless of the A and B who should successfully updated, its update will be updated after the cover . XXX optimistic locking mechanism introduced to avoid such problems. In the example just assumed that A and B take the same time to the data, then the version number is 10, A to update, after the update is successful, the value 12, the version of 11. When B is updated, because it is based on version 10, then the server will reject the update, returns the version error, to avoid updating A is covered.

Third, the two locks of thinking

  1, pessimistic locking problems with a lot of slow response under high concurrency, and there are restrictions on the query, to be more careful when writing code, but its success rate, fewer retries. Is suitable for a low response speed requirements, retry costly scene.

  2, except in the case other than 1, I think your choice of optimistic locking is still very convenient.

     

 

  

  

 

Guess you like

Origin www.cnblogs.com/gywfight/p/11646816.html