Fair lock and non-fair lock

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.