Optimistic locking, pessimistic locking, this one is enough!

1. Optimistic locking

Optimistic locking the name suggests is very optimistic at the time of the operation, that the operation does not generate concurrency problems (no other threads to modify the data), it will not be locked. But when the judge will update the other threads before that there is no data can be modified, typically use 版本号机制or CAS(compare and swap)算法implementation.
Simple to understand: The data here, think too much, even though you use, a problem I'm the counseling, ie after transaction rollback operation fails, prompt. The version number, the CAS nature of these two methods is the same: If the conditions are satisfied, do you want to do, is conditional or fast atoms, consuming almost do not count.

1.1 version number of mechanisms

1.1.1 implement routines:

  • When removing the recording, obtaining the currentversion
  • When updating, to bring thisversion
  • Execution of updates, set version = newVersion where version = oldVersion
  • If versionnot, it will update failed

Core SQL:

update table set name = 'Aron', version = version + where id = #{id} and version = #{version};

1.1.2 Examples -Mybatis-plus optimistic locking achieve

Click to view original  Mybatis-plus optimistic locking achieve

1.2 CAS algorithm

Another technique optimistic locking technique, when multiple threads attempt to use the CAS simultaneously update the same variable, only one thread can update the values ​​of variables, and other threads have failed, the failure of the thread will not be suspended, and the competition is being told in failure, and you can try again.

CAS Operation includes three operands:

  • You need to read and write memory locationsV
  • Prospectively compare the original valueA
  • The new value of the proposed writtenB

If the memory location Vof the original value of the expected value Amatch, the processor will automatically update the location value to the new value B. Otherwise, the processor does nothing. In either case, it will be the  CAS return value of the position before the instruction (in the  CAS case of some special cases will be returned only  CAS if successful, without extracting the current value). CAS Effectively explains, "I think the location  V should contain the value  A; If you include this value, then  B put in this position; otherwise, do not change the location, just tell me the value of this location can now" this is actually optimistic locking conflict check the data update + principle is the same.

1.2.1 Examples packet achieve -concurrent

Because javaof CAShaving both  volatile read and volatilewrite memory semantics, and Javacommunication between threads now have the following four ways:

  1. AThread write volatilevariables, then Bthread read this volatilevariable.
  2. AThread write volatilevariables, then Bthread with CASupdates this volatilevariable.
  3. AThread with CASupdates a volatilevariable, then Bthread with CASupdates this volatilevariable.
  4. AThread with CASupdates a volatilevariable, then Bthread read this volatilevariable.

JavaThe CASuse efficient machine-level instructions provided on the atoms of modern processors, the atomic instruction atomically memory performs a read - modify - key synchronization for writing, which is in a multi-processor (essentially to support an atomic read - modify - write instruction computer, a Turing machine is sequentially calculated equivalent asynchronous machine, so any modern multi-processor will be able to support a memory atomic read - modify - write operation instruction atoms ). Meanwhile, the volatilevariable read / write and CAScommunicate between threads can be achieved. These features put together, they form a whole concurrentcornerstone of the package can be realized.

Careful analysis concurrentpackage source code to achieve, you will find a common realization mode:

  1. First, declare shared variables volatile;  
  2. Then, a condition updating CAS atoms to achieve synchronization between threads;
  3. At the same time, cooperate to volatileread / write and CAShas volatileread and write memory semantics to implement threads

1.2.2 shortcomings

  • ABAproblem

For example, a thread T1from a memory location Vtaken out A, this time another thread T2is also removed from memory A, and T2carried out some operations become B, then T2turn Vthe data into position A, this time threads T1were CASoperating memory is still found A, then T1the operation was successful. Although the thread T1of CASsuccessful operation, but there may be problems lurking.

  • Large overhead long cycle time

Spin CAS(unsuccessful, the cycle has been executed, until it succeeds) if not successful for a long time, will bring a very large execution overhead CPU. If the JVMsupport provided by the processor pauseinstructions so there will be some efficiency improvement, pauseinstruction serves two purposes, first it may delay pipelined execution of instructions ( de-pipeline), so that CPUdoes not consume too many resources to perform the delay time depends on the specific implementation version, on some processors delay time is zero. The second memory which can be avoided by order of the conflict (when exiting the loop memory order violation) caused by CPU pipeline is cleared ( CPU pipeline flush), thereby increasing the CPUefficiency of the implementation.

  • Atomic operation can only guarantee a shared variable

When performing operations on a shared variable, we can use the CAS cycle approach to ensure an atomic operation, but when multiple shared variables operating cycle CAS can not guarantee atomic operations, this time you can use the lock, or a tricky way, is to merge multiple shared variables into a shared variable to operate. For example, there are two shared variables i = 2,j = a, merge it ij = 2a, then use CASto operate ij. From Java 1.5Providing start JDK AtomicReferenceclasses to guarantee atomicity references between objects, you can put an object in the plurality of variables to CASoperate.

2. pessimistic locking

Always assume the worst case (the idea is very pessimistic), each thought the other thread changes, so will add (pessimistic) lock when fetching data. Once locked, when different threads execute simultaneously, only one thread of execution, other threads wait at the entrance until the lock is released.

In pessimistic locking MySQL, Javaa wide range of use

  • MySQLA read lock, write lock, line lock, etc.
  • JavaThe synchronizedkeyword

3. Summary

Read more small chance of conflict, optimistic locking.
Write more big chance of conflict, pessimistic locking.

 

Guess you like

Origin www.cnblogs.com/sunsky303/p/11468801.html