Fair locks and unfair locks
Fair lock: similar to the canteen dozen rice, according to the order of the lock to obtain the lock similar to the toilet squat first come later
Fair lock is very fair in the concurrent environment each thread in the acquisition of the lock at the same time will first check the lock maintenance wait queue, if it is empty, or the current thread is waiting to occupy the lock, otherwise join the wait queue, in accordance with the RULES of FIFO from the queue to get their own
Unfair lock: The order in which multiple threads obtain locks is not in accordance with the order in which they apply for locks. It is possible that the thread applying for locks later may obtain the locks first than the thread applying for locks earlier. In the case of high concurrency, priority reversal and starvation may occur
If an unfair lock comes up, try to possess the lock. If the lock fails, adopt a similar way to the fair lock
ReentrantLock can specify the Boolean type of the constructor to get a fair lock or an unfair lock
advantage
The advantage of an unfair lock is that the throughput of a fairly large lock is also an unfair lock for synchronized.
Reentrant lock (recursive lock)
If the same thread acquires the lock, the inner recursive function can still acquire the acquired code. If the same thread acquires the lock, the inner recursive function automatically acquires the lock. That is to say, the thread can access any block of code that it already owns and synchronizes with the lock
ReentrantLock and synchronized typically avoid deadlocks
spinlocks
Try to acquire the lock but do not block immediately. Instead, try to acquire the lock in a loop
Similar to I want to ask the teacher a question, but the teacher has something on the phone, I have two ways: one is to wait there blocked, one is to go down to smoke a cigarette and come back later. If I can’t finish it, I will continue to do my own work and come back to see the cycle
Hand-written spin lock
Thread A calls myLock and holds it for 5 seconds. Thread B comes in and finds that the current thread does not hold the lock empty. It has to spin until thread A releases the lock and thread B grabs itCopy the code
Exclusive lock (write)/shared lock (read)/mutex lock/read-write lock
Exclusive lock: the lock can only be held by one thread at a time. An exclusive lock for both ReentrantLock and Synchronized
Shared lock: The lock can be held by multiple threads
For ReentrantReadWriteLock, the read lock is shared and the write lock is exclusive
The sharing of read locks ensures that concurrent reads are very efficient. Read/write, write/read, and write processes are mutually exclusive