Pessimistic lock (Pessimistic Lock), as the name implies, is very pessimistic, every time to take the data when they think others will change, so every time when the data are locked, so that other people want to take this data will block until it gets the lock. Traditional relational database in the use of a lot of this locking mechanism, such as row locks, table locks, read locks, write locks, etc., are in operation before the lock.
optimistic Lock (Optimistic Lock), as the name implies, is very optimistic, every time to take the data when they think others will not be modified, so will not be locked, but in the update will be judged in the period when others have to update this data, you can use the version number and other mechanisms. Optimistic locking is useful for multi-read application types, which can improve throughput, such as the fact that a database provides an optimistic lock similar to the write_condition mechanism.
The two kinds of locks have advantages and disadvantages, not to think of one better than the other, like the optimistic lock for less write, that is, the conflict really rarely occurs, this can save the lock overhead, increase the overall system throughput. However, if there is frequent conflict, the upper application will continue to retry, which is to reduce the performance, so in this case, pessimistic locking is more appropriate.
A spin lock is implemented in a loop in which the current thread is continuously executing, and can enter the critical section when the condition of the loop is changed by another thread. As follows
Public classSpinLock {PrivateAtomicreference<thread> sign =NewAtomicreference<>(); Public voidLock () {Thread current=Thread.CurrentThread (); while(!sign. Compareandset (NULL, current)) { } } Public voidunlock () {Thread current=Thread.CurrentThread (); Sign. Compareandset (Current,NULL); }}
With CAS atomic operations, the lock function sets owner to the current thread and predicts that the original value is empty. The Unlock function sets owner to NULL, and the predicted value is the current thread.
When a second thread calls the lock operation because the owner value is not NULL, the loop is always executed until the first thread calls the Unlock function to set the owner to NULL, and the second thread can enter the critical section.
Because the spin lock simply keeps the current thread executing the loop body without changing the thread state, the response is faster. However, when the number of threads increases continuously, performance degrades significantly because each thread needs to execute, consuming CPU time. If the thread is not competing fiercely, and the time period of the lock is maintained. Suitable for use with spin locks.
Note: This example is an unfair lock, and the order in which the locks are obtained is not carried out in the order in which they enter lock.
Java Multithreading: Optimistic lock, pessimistic lock, spin lock