Fair lock, unfair lock, reentrant lock, recursive lock, spin lock

List of topics: juejin, github, smartblue, cyanosis, channing-cyan, fancy, hydrogen, condensed-night-purple, greenwillow, v-green, vue-pro, healer-readable, mk-cute, jzman, geek-black, awesome-green, qklhk-chocolate

Contribution Subject:Github.com/xitu/juejin…

theme: juejin highlight:

Fair lock | not fair lock In the process of contract awarding and already created designated constructor Boolean type to get fair or not fair lock, lock is a fair lock by default.

What’s the difference between a fair lock and an unfair lock? A fair lock is one in which multiple threads acquire locks in the order in which they are applied. An unfair lock means that when multiple threads acquire locks, the sequence of acquiring locks is not in accordance with the sequence in which they apply for locks. The thread that applies for locks later may obtain them first. In the case of high concurrency, priority reversal or starvation may occur.

The differences between the two are as follows: Fair lock: It is fair. When each thread obtains a lock, it first checks the queue maintained by the lock. If null, the current thread is first in the queue and holds the lock, otherwise it is added to the queue and then fetched from the queue according to FIFO rules.

Unfair lock: rude, try to possess the lock directly, if failed, then use a similar mechanism of fair lock. This way the performance is good. (Synchronized is also an unfair lock.)

A reentrant lock (also known as a recursive lock) is a code that can be acquired by an in-memory recursive function even after the lock is acquired by an outer function of the same thread. When the same thread acquires a lock from the outer layer, the inner method acquires the lock automatically. That is, a thread can enter the synchronized code block of any lock it already owns. Already/synchronized is typical of the re-entrant locking. The greatest benefit of reentrant locks is to avoid deadlocks.

A spin lock means that the thread attempting to acquire the lock does not block immediately, but instead attempts to acquire the lock in a circular manner. This has the advantage of reducing the cost of thread switching up and down, but has the disadvantage of looping or consuming CPU. Spin benefit: Loop comparisons until successful, no WAIT blocking.