Lock fair / unfair locks (multi-threaded execution order dimension)
Conceptual understanding
- Fair locks: lock before waiting to see if there is a thread, the thread top surface of any priority, first come first served .
- Unfair as: thread locking direct attempt to acquire the lock , not automatically get the tail to wait.
example
- ReentrantLock support both lock
// create a fair and non-locking, non-default fair locks Lock nonFairLock= new ReentrantLock(); Lock nonFairLock= new ReentrantLock(false); // create a fair lock structure parameter passing true Lock fairLock= new ReentrantLock(true);
Applicable scene
- More direct use of unfair lock: Lock unfair 5-10 times higher than the fair-locking performance, because the need to maintain a fair lock queue in the case of multi-core, if the current thread is not the first queue can not get a lock, an increase of thread switching times.
Lock optimistic / pessimistic locking (dimensions multithreading share data)
Conceptual understanding
- Pessimistic locking: suppose will happen concurrency violation , by blocking all other threads to ensure data integrity.
- Optimistic locking: assuming that does not happen concurrency conflicts directly unlocked to complete an update, if conflict returns failure.
example
- Pessimistic locking: Synchronized multi-thread synchronization, exclusive, will be prone to deadlock.
- Optimistic locking: CAS mechanism, in short, there will be three operands, the current value of V memory variables, the expected value of the variable A, is about to update the value of B, when the need to update the variable, the variable value V directly and the expected value A , if the same, then B is directly updated; if not identical, then the current value of the variable to a desired value V refresh, and then try to re-update the comparison.
Applicable scene
- Optimistic locking: apply to data contention is not serious / retry little cost / fast requires a corresponding scene.
- Pessimistic locking: apply to serious contention data / retry high price scenario.