Pessimistic optimistic locking lock, to see which one is enough!

Optimistic locking, pessimistic locking is its use of perspective. (PS: for example, to achieve internal ReentrantLock uses CAS and spin to improve performance, but its use of perspective, the idea is to use pessimistic locking.)

1. Optimistic locking

Optimistic locking: As the name suggests is a 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, usually using the version number mechanism or CAS (the Compare and swap) algorithm. (PS: CAS is the atomic instruction)
is simple to understand: the data here, think too much, even though you use, and then fix the problem, namely the transaction is rolled back after the operation fails, tips, updates data.

Atoms generic implementation class:

  1. Declare shared variables to be volatile
  2. CAS use atomic updates to achieve synchronization between threads
  3. Read / write variables and volatile CAS has read and write volatile memory semantics for communication between threads

2. pessimistic locking

Pessimistic locks: always assume the worst case, each believes the other thread changes, so will add (pessimistic) lock when fetching data. Once locked, when different threads execute simultaneously, only one thread can execute other threads to wait at the entrance until the lock is released.

3. Two lock usage scenarios

From the above describes two locks, we know that other kinds of locks have advantages and disadvantages, can not be considered to be a good alternative:

  1. Optimistic locking apply to write fewer scenes under (read more scene), that is, when the conflict is really rare, so the lock can save the cost, increase the overall throughput of the system. But if the case is to write, usually it will often produce conflict, which leads to the upper application will continue to be retry, such but rather affects the performance
  2. Pessimistic locking apply to write more scenes under

4. References

  1. Interview essential optimistic and pessimistic locking lock

Guess you like

Origin www.cnblogs.com/wengle520/p/12368376.html