Java Web Combat 11 - Common Locking Strategies for Advanced Multithreading

Hello everyone, this article brings you common lock strategies in multithreading, and we will explain 6 types of locks to you

  1. Optimistic lock VS pessimistic lock
  2. Ordinary mutex VS read-write lock
  3. Heavyweight locks vs lightweight locks
  4. Spin lock VS pending wait lock
  5. Fair lock VS unfair lock
  6. Reentrant locks vs non-reentrant locks
  7. common interview questions

For the common lock strategy, this is the content that you love to test in the interview but you don’t need it for work. You
can understand it and remember it. I
recommend you to jump to this for better viewing effect. I also posted
the link of the previous article here.

The puppy said that he would invite everyone to have a drink, so quickly say to me: "Thank you puppy"
insert image description here
insert image description here

Common Locking Strategies

The lock strategy refers to: when we add the lock, how do we add it
? The lock strategy mentioned here has basically nothing to do with the language, and other languages ​​​​also involve "lock strategies"

1. Optimistic lock VS pessimistic lock

Optimistic lock: predict that the probability of the next lock conflict is not high , you need to do one type of operation
Pessimistic lock: predict the probability of the next lock conflict is high , you need to do another type of operation

Take a chestnut:
the epidemic caused the school to be closed
. Some people are nervous. Go to the supermarket to grab some snacks -> Optimistic
lock
.

Optimistic locks are relatively less costly; pessimistic locks are relatively more costly

We have introduced synchronized before. It is both a pessimistic lock and an optimistic lock, that is, an adaptive lock. The
current lock conflict probability is not high, and it runs in an optimistic lock mode. It is often executed in pure user mode.
Once the lock conflict is found to be large, the To run in a pessimistic lock mode, it is often necessary to enter the kernel to suspend and wait for the current thread

2. Ordinary mutex VS read-write lock

Synchronized is an ordinary mutex, and two locking operations will cause competition

The read-write lock refines the locking operation and divides it into "read lock" and "write lock".
Case 1:
Thread A tries to add a write lock, and
thread B tries to add a write lock.
Thread A and thread B compete with each other, which is different from ordinary There is no difference between the locks. Case
2:
Thread A tries to add a read lock.
Thread B tries to add a read lock.
Thread A and thread B do not compete, and the lock is equivalent to no addition
(multi-threaded reading, does not involve modification, and is thread-safe)
3:
Thread A tries to add a read lock.
Thread B tries to add a write lock.
Thread A and thread B compete, which is no different from ordinary locks.

Only case 2 (both threads are read locks) is thread-safe

The read-write lock is to treat the read operation and the write operation differently. The Java standard library provides ReentrantReadWriteLockthe class to implement the read-write
lock.

  • ReentrantReadWriteLock.ReadLockClass represents a read lock. This object provides lock / unlockmethods to lock and unlock.
  • ReentrantReadWriteLock.WriteLockClass represents a write lock. This object also provides lock / unlockmethods to lock and unlock.

3. Heavyweight lock VS lightweight lock

Heavyweight locks mean that the cost of locks is relatively large and more work is done.
Lightweight locks mean that the cost of locks is relatively small and less work is done

Pessimistic locks, often heavyweight locks
Optimistic locks, often lightweight locks
but not absolute

So what does it mean to do more work and do less work?
We generally believe that locks must be mutually exclusive, and that mutual exclusion must have a source of power. To
implement a lock in Java, we need to use the synchronized keyword ( ReentrantLock will be degraded in the future)
The locks implemented in Java are mainly the synchronized and ReentrantLock mechanisms provided by the JVM. The reason
why the JVM can implement the lock mechanism is because the operating system provides a mutex. The
reason why the operating system can lock , because the CPU provides some instructions for locking, which can guarantee atomic operations.
image.png
Heavyweight locks mainly rely on the locks provided by the operating system. Using the locks provided by the operating system, it is easy to block and wait for
lightweight locks. Try to avoid using the locks provided by the operating system, try to complete the function in the user mode, that is, try to avoid switching between the user mode and the kernel mode, and try to avoid hanging waiting (blocking waiting)

Synchronized is an adaptive lock, which is both a lightweight lock and a heavyweight lock.
It is also determined according to the lock conflict situation.
The low conflict is a lightweight lock, and the high conflict is a heavyweight lock.

4. Spin lock VS pending wait lock

Spin locks and pending locks are viewed in more depth, which is equivalent to the innermost layer of analysis

Spin lock: When we find a lock conflict, it will not suspend waiting, it will quickly try again to see if the lock can be acquired (super licking dog),
it is equivalent to a while loop to acquire the lock state
once the lock is released , you can get it immediately
If the lock is not released, it will consume a lot of CPU
Spin lock is lighter and more efficient

Suspend waiting for locks: When lock conflicts are found, suspend waiting.
Once the lock is released, it cannot be acquired immediately.
When the lock is occupied by other threads, CPU resources will be given up. Suspending
and waiting for locks is more heavy and less efficient

Spin lock is the specific implementation of lightweight lock
Hanging and waiting lock is the specific implementation of heavyweight lock

Spin locks are lightweight locks and optimistic locks
Hanging waiting locks are heavyweight locks and pessimistic locks

When synchronized is used as a lightweight lock, the interior is a spin lock.
When synchronized is used as a heavyweight lock, the interior is a pending lock

5. Fair lock VS unfair lock

What kind of situation is fair?
It is fair if it conforms to the rule of "first come, first served"

Those who come first will be in the front row first. Those who come late will be in the back row

Take a chestnut:
image.png
In the operating system, the default lock competition rules are unfair, without consideration of first come, first served.
If you want to use fair locks, you need to use additional data structures for control and implementation.
So synchronized is an unfair lock

6. Reentrant lock vs non-reentrant lock

image.png

7. Common Interview Questions

  1. How do you understand optimistic locking and pessimistic locking, and how do you implement them?

Pessimistic locks believe that the probability of multiple threads accessing the same shared variable conflicts is high, and will actually lock before each access to the shared variable. Optimistic
locking believes that the probability of multiple threads accessing the same shared variable conflicts is not high. It will actually lock, but directly try to access the data. While accessing, identify whether the current data has an access conflict.
The implementation of pessimistic locking is to lock first (for example, with the help of the mutex provided by the operating system), and then operate the data after obtaining the lock . Wait if you can’t get the lock.
The implementation of optimistic lock can introduce a version number. Use the version number to identify whether the current data access conflicts. (Refer to the above figure for implementation details).

  1. Introduce read-write lock?

The read-write lock is to lock the read operation and the write operation separately.
The read lock and the read lock are not mutually exclusive.
The write lock and the write lock are mutually exclusive.
The write lock and the read lock are mutually exclusive.
The read-write lock is the most It is mainly used in the "frequent read, infrequent write" scenario.

  1. What is a spin lock, why use a spin lock strategy, and what are the disadvantages?

If the lock acquisition fails, try to acquire the lock again immediately, and loop infinitely until the lock is acquired. If the lock acquisition fails for the first time, the second attempt will come in a very short time. Once the lock is released by other threads, you can Get the lock at the first time.
Compared with hanging and waiting for the lock,
the advantages: no CPU resources are given up, once the lock is released, the lock can be acquired at the first time, which is more efficient. It is very useful in scenarios where the lock holding time is relatively short .Disadvantage
: If the lock is held for a long time, CPU resources will be wasted.

  1. Is synchronized a reentrant lock?

It is a reentrant lock.
A reentrant lock means that two consecutive locks will not cause deadlock.
The way to achieve this is to record the thread identity held by the lock in the lock, and a counter (recording the number of locks). If it is found that the currently locked thread is the thread holding the lock, the count will be incremented directly.

This is the end of this article.
If it is helpful, please press three times.
The puppy will treat you to a drink
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/m0_53117341/article/details/129529232