Two types of locks are available in the Java Reentrantlock constructor: Create fair and unfair locks (default). The code is as follows:
Public Reentrantlock () {
Sync = new Nonfairsync ();
}
Public Reentrantlock (Boolean fair) {
Sync = Fair? New Fairsync (): New Nonfairsync ();
}
In the fair lock, the thread acquires the lock in the order in which they make the request, but in the unfair lock, it is allowed to ' queue jump ': When a thread requests an unfair lock, if the lock becomes available while the request is made, the thread skips all waiting threads in the queue and acquires the lock. Unfair Reentrantlock does not advocate queue jumping, but does not prevent a thread from jumping in at the right time.
In a fair lock, if another thread holds the lock or if another thread waits for it in the waiting queue, the new thread of the request is put into the queue. Rather than a fair lock, the new request thread is placed in the queue only if the lock is held by a thread.
The cause of the unfair lock performance is higher than the fair lock performance:
There is a serious delay between recovering a suspended thread and actually running the thread.
Assume that thread a holds a lock, and thread B requests the lock. Because the lock is held by a, B will be suspended. When a releases the lock, B is awakened, so B tries to acquire the lock again. At the same time, if thread C also requests this lock, then C is likely to get, use, and release the lock before B is fully awakened. This is a win-winning situation: B The time to get the lock is not postponed, C acquired the lock earlier, and the throughput increased.
A fair lock should be used when the lock is held for a relatively long time or the average interval between requests for locks is longer. In these cases, the throughput increase caused by the queue jump (while the thread is still in the wake-up process when the lock is in a usable state) may not appear.
Fair lock and non-fair lock