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 current
version
- When updating, to bring this
version
- Execution of updates,
set version = newVersion where version = oldVersion
- If
version
not, it will update failed
Core SQL:
update table set name = 'Aron', version = version + 1 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 locations
V
- Prospectively compare the original value
A
- The new value of the proposed written
B
If the memory location V
of the original value of the expected value A
match, 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 java
of CAS
having both volatile
read and volatile
write memory semantics, and Java
communication between threads now have the following four ways:
A
Thread writevolatile
variables, thenB
thread read thisvolatile
variable.A
Thread writevolatile
variables, thenB
thread withCAS
updates thisvolatile
variable.A
Thread withCAS
updates avolatile
variable, thenB
thread withCAS
updates thisvolatile
variable.A
Thread withCAS
updates avolatile
variable, thenB
thread read thisvolatile
variable.
Java
The CAS
use 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 volatile
variable read / write and CAS
communicate between threads can be achieved. These features put together, they form a whole concurrent
cornerstone of the package can be realized.
Careful analysis concurrent
package source code to achieve, you will find a common realization mode:
- First, declare shared variables
volatile
; - Then, a condition updating CAS atoms to achieve synchronization between threads;
- At the same time, cooperate to
volatile
read / write andCAS
hasvolatile
read and write memory semantics to implement threads
1.2.2 shortcomings
ABA
problem
For example, a thread T1
from a memory location V
taken out A
, this time another thread T2
is also removed from memory A
, and T2
carried out some operations become B
, then T2
turn V
the data into position A
, this time threads T1
were CAS
operating memory is still found A
, then T1
the operation was successful. Although the thread T1
of CAS
successful 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 JVM
support provided by the processor pause
instructions so there will be some efficiency improvement, pause
instruction serves two purposes, first it may delay pipelined execution of instructions ( de-pipeline
), so that CPU
does 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 CPU
efficiency 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 CAS
to operate ij. From Java 1.5
Providing start JDK AtomicReference
classes to guarantee atomicity references between objects, you can put an object in the plurality of variables to CAS
operate.
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
, Java
a wide range of use
MySQL
A read lock, write lock, line lock, etc.Java
Thesynchronized
keyword
3. Summary
Read more small chance of conflict, optimistic locking.
Write more big chance of conflict, pessimistic locking.