Classification and use of locks in java

The locks in java are divided into the following types

  • Optimistic lock, pessimistic lock
  • Exclusive lock, shared lock
  • Fair lock, unfair lock
  • Mutex, read-write lock
  • Reentrant lock
  • Segment lock
  • Lock upgrade (no lock -> deflection lock -> lightweight lock -> heavyweight lock)  

The above are some lock terms. These categories do not all refer to the state of the lock. Some refer to the characteristics of the lock, and some refer to the design of the lock. The content summarized below is a certain explanation of each lock term.

1. Optimistic lock & pessimistic lock

Optimistic locking and pessimistic locking do not specifically refer to two types of locks. They are concepts or ideas defined by people. They mainly refer to the perspective of concurrent synchronization.

Optimistic lock: Optimistic lock thinks that no other threads will change the data when a thread is going to get the data, so it will not be locked, but when updating, it will judge whether others have updated the data during this period.

Implementation method: CAS mechanism, version number mechanism (record database version)

CAS is an optimistic locking technology. When multiple threads try to use CAS to update the same variable at the same time, only one thread can update the value of the variable, and other threads fail. The failed thread will not be suspended, but will be Inform you that you have failed in this competition and you can try again.

 

                                                                        Version number mechanism to achieve optimistic locking

ABA problem:

The ABA problem is a problem in the CAS mechanism, his description is like this. We directly draw a picture to demonstrate,

What does that mean? That is, a thread changes data A into B, and then becomes A again. At this time, when another thread reads it, and finds that A has not changed, it mistakes it for the original A. This is the famous ABA problem. What are the consequences of ABA problems? Let us give an example.

A thief who stole money from someone else’s house and then returned it. Is it still the original money? Is your wife back after cheating, is it still the original wife? The ABA problem is the same, if it is not solved properly, it will bring a lot of problems. The most common problem is funding, that is, if someone misappropriates your money, you pay it back before you find it out. But others have broken the law.

Solution: add a timestamp or the version number to compare the version number each time

Pessimistic lock : always assume the worst case, think that others will modify it every time you get the data, so every time you get the data, you will lock it, so that others will block until it gets the lock if they want to get the data . For example, the implementation of the synchronized keyword of the synchronization primitive in Java is a pessimistic lock.

Pessimistic concurrency control is actually a conservative strategy of "fetch locks before access", which provides a guarantee for the security of data processing.

The use of pessimistic locks in Java is the use of various locks.

The use of optimistic locking in Java is lock-free programming, and CAS algorithm is often used. A typical example is the atomic class, which realizes the update of atomic operations through CAS spin.

2. Exclusive lock/shared lock

Two kinds of locks are just a concept

Exclusive lock: the lock can only be held by one thread at a time

Shared lock: the lock can be held by multiple threads

For example:

Synchronized is an exclusive lock;

Reentrant Lock is an exclusive lock;

The read lock ReadLock in ReentrantReadWriteLock is a shared lock, and the write lock WriteLock is an exclusive lock.

Exclusive locks and shared locks are realized by AQS (AbstractQueuedSynchronizer), and by implementing different methods, exclusive or shared locks can be realized.

3. Mutex/read-write lock

The exclusive lock/shared lock mentioned above is a concept, and the mutual exclusion lock/read-write lock is a concrete realization.

The specific implementation of mutual exclusion locks is synchronized and ReentrantLock. ReentrantLock is a new feature of JDK1.5. Using ReentrantLock can completely replace the synchronized traditional lock mechanism and is more flexible.

Read-write lock specific implementation is read-write lock ReadWriteLock.

 

4. Reentrant lock

 Reentrant lock, also known as recursive lock, means that when the same thread acquires the lock in the outer method, it will automatically acquire the lock when it enters the inner method. It is a bit abstract, there will be a code example below.

  For Java ReetrantLock, it can be seen from the name that it is a reentrant lock, and its name is Re entrant Lock.

  For Synchronized, it is also a reentrant lock. One advantage of reentrant locks is that deadlocks can be avoided to a certain extent.

synchronized void setA() throws Exception{
   Thread.sleep(1000);
   setB();
}
 
synchronized void setB() throws Exception{
   Thread.sleep(1000);
}

The above code is a feature of a reentrant lock. If it is not a reentrant lock, setB may not be executed by the current thread, which may cause a deadlock.

Advantages: avoid deadlock

5. Fair lock & unfair lock

A fair lock means that multiple threads acquire locks in the order in which they apply for locks.

  An unfair lock means that the order in which multiple threads acquire locks is not in the order of applying locks. It is possible that the thread that applies later will get the lock first than the thread that applies first. It may cause priority inversion or starvation.

  For Java ReetrantLock, the constructor specifies whether the lock is a fair lock, and the default is an unfair lock. The advantage of unfair locks is that throughput is greater than fair locks.

  For Synchronized, it is also an unfair lock. Since it is not like ReentrantLock that implements thread scheduling through AQS, there is no way to make it a fair lock.

6. Segmented lock

Segmented lock is actually a lock design, not a specific type of lock. For ConcurrentHashMap, its concurrency is achieved through the form of segmented locks to achieve efficient concurrent operations.

  Let's take ConcurrentHashMap to talk about the meaning and design idea of ​​segment lock. The segment lock in ConcurrentHashMap is called Segment, which is similar to the structure of HashMap (the implementation of HashMap in JDK7 and JDK8), that is, it has an Entry array inside. Each element in is a linked list; at the same time, it is a ReentrantLock (Segment inherits ReentrantLock).

  When the put element is needed, it is not to lock the entire hashmap, but to know which segment it is to be placed in through the hashcode, and then lock this segment, so when multi-threaded puts, As long as it is not placed in a segment, true parallel insertion is achieved.

  However, when counting the size, when obtaining the global information of the hashmap, it is necessary to obtain all the segment locks for statistics.

  The design purpose of the segmented lock is to refine the granularity of the lock. When the operation does not need to update the entire array, only one item in the array is locked.

7. Bias lock & lightweight lock & heavyweight lock

These three locks refer to the state of the lock and are for Synchronized. In Java 5, a lock escalation mechanism is introduced to achieve efficient Synchronized. The status of these three locks is indicated by the field in the object header of the object monitor.

  Biased lock means that a piece of synchronized code has been accessed by a thread, then the thread will automatically acquire the lock. Reduce the cost of acquiring locks.

  Lightweight lock means that when the lock is a biased lock, it is accessed by another thread, the biased lock will be upgraded to a lightweight lock, and other threads will try to acquire the lock through spin, without blocking, and improve performance .

  A heavyweight lock means that when the lock is a lightweight lock, although another thread is spinning, the spin will not continue forever. When the spin is a certain number of times, the lock has not been acquired, it will enter the block , The lock expands into a heavyweight lock. Heavyweight locks will block the thread he applied for and reduce performance.

Comparison of advantages and disadvantages of locks

lock advantage Disadvantage Applicable scene
Bias lock Locking and unlocking do not require additional consumption, and there is only a nanosecond gap between implementing asynchronous methods If there is lock competition between threads, it will bring additional lock cancellation costs Suitable for scenarios where only one thread accesses the synchronized block
Lightweight lock Competing threads will not be blocked, which improves the response speed of the program If the thread that cannot get the lock contention uses spin, it will consume the CPU Pursue response time, lock occupying time is very short
Heavyweight lock Thread competition does not use spin and does not consume CPU Thread blocking, slow response time Pursue throughput, lock takes a long time

8. Spin lock

In Java, spin lock means that the thread trying to acquire the lock will not be blocked immediately, but will try to acquire the lock in a loop. The advantage of this is to reduce the consumption of thread context switching. The disadvantage is that the loop consumes CPU.

 

 

Guess you like

Origin blog.csdn.net/a447332241/article/details/107955291