Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

The difference between java Fair Lock and unfair Lock

Shulou Source: shulou.com Published: 2022-06-02 06:59:46 10月02日 Update

This article mainly introduces "the difference between java fair lock and unfair lock". In daily operation, I believe that many people have doubts about the difference between java fair lock and unfair lock. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "the difference between java fair lock and unfair lock". Next, please follow the editor to study!

Fair lock: indicates that the order in which the thread acquires the lock is based on the thread startup order, that is, first come, first served, first out.

Unfair lock: indicates that the acquisition lock is acquired at random, and starting first does not guarantee that the lock will be acquired first.

Let's use two examples to demonstrate fair locking and unfair locking.

Fair lock

We see that the running order of the output thread is the same as the order in which the thread acquires the lock. This is the characteristic of fair lock, first come, first served. Let's take a look at unfair locks.

Unfair lock

We just need to change the parameter of the Userinfo object in the test class to true to false.

We see that there is no rule in the order in which threads acquire locks and the order in which threads execute, that is, unfair locks, and there is no guarantee that the thread that executes first will be able to get the lock first.

The difference between fair locks and unfair locks:

The performance of fair lock is lower than that of unfair lock.

The default construction parameter of the ReentrantLock class is false, that is, an unfair lock by default.

At this point, the study on "the difference between java fair lock and unfair lock" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Threads order learning parameters that is performance more first-come guarantee help utility consistency and then two that is examples advanced objects articles methods Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Technology Xiaomi MySQL Apple