In a Web application, an account will have N more fields involving numbers. Such as the amount of an account, points and so on. These fields refer to increments and subtractions. If you are in a test environment, it is up to the programmer or tester to manually click. Usually you can’t find the problem.

Once you’re in the formal environment. There are real users to do the operation, it is easy to appear inexplicable amount and flow record inconsistent situation. If you don’t have enough experience, it’s hard to identify problems.

As I understand it, the industry generally uses three solutions

  • 1. Use message queues
  • 2. The pessimistic locking
  • 3. Optimistic locking

Because bloggers themselves are in small companies, they have no hands-on experience with message queues. So this article focuses on the latter two.

Pessimistic locking

From the name, it means that the possibility of concurrency is guaranteed to occur, preventing data from being corrupted in the first place.

Common handling methods:

Lock the database. Examples include RowLock in SQL Server and for Update in Mysql

Advantages: No data problems in the case of no program problems

Cons: Poor performance, and database locking is a very resource-intensive behavior

Optimistic locking

Optimistic locks are the opposite of pessimistic locks. Assume that there will be no concurrency problems. Only when committing a change, check to see if the current piece of data has changed.

Common handling methods:

Adds a column to the database. Record the version number of the current change. During each change, check whether the version number is consistent with that queried earlier. If yes, check whether the version number is consistent with that queried earlier. The modification succeeded. The modification is inconsistent and cannot be modified. You need to reload the query data once, and then loop through the actions

The pseudocode is as follows:

While (true){selct id,money,version from table; ndex =1; Update table set money = money, Version = (version+1) where id = @id and version = version // Check whether the update succeeds. } // index+=1; if(index>3){ break; }}Copy the code

Advantage of optimistic lock: It can realize lock-free operation, and the performance is much higher than pessimistic lock

Disadvantages of optimistic lock: there are dirty read problems, and the number of queries will be several times more than pessimistic lock

Knowing these two methods, you can already apply them to all kinds of large and small scale applications.