Java concurrent reading notes: lock and reentrantlock
Lock is located in Java util. concurrent. Under the locks package, there is a thread synchronization mechanism, just like synchronized blocks. However, lock is more flexible and complex than synchronized blocks.
Not much to say, let's directly look at the official documents describing the concepts and functions related to the lock interface. Today is another day to read the English documents and translate and understand them.
1、 Lock inheritance
2、 Interpretation of official documents
3、 Interpretation of lock interface method
Get lock. If the lock is not available, the current thread is disabled for thread scheduling purposes and is dormant until the lock is obtained.
If the current thread is not interrupted, the lock is obtained. If the lock is available, acquire the lock and return immediately.
If the lock is not available, the current thread is disabled for thread scheduling purposes and will remain dormant.
The following two situations will stop the current thread from sleeping:
Interruptedexception will be thrown and the interrupt status of the current thread will be cleared when the following two conditions occur on the current thread.
Try to acquire the lock. If the lock is idle, acquire the lock and return true immediately. If the lock is unavailable, false is returned immediately.
Typical use of this method:
Lock lock = ...;
//确保锁在被获取时被解锁
if (lock.tryLock()) {
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}
This method is an overloaded method of trylock(), and the two parameters are expressed as:
If it is idle within a given waiting time and the current thread is not interrupted, the lock is obtained. If the lock is available, this method immediately obtains the lock and returns true. If the lock is not available, the current thread will be disabled for thread scheduling purposes, and the thread will always be in sleep.
The following three situations will stop the current thread from sleeping:
Interruptedexception will be thrown and the interrupt status of the current thread will be cleared when the following two conditions occur on the current thread.
Returns a false value if the specified wait time expires. If the time is less than or equal to 0, the method will never wait.
Release the lock, corresponding to lock(), trylock(), trylock (long, timeunit), lockinterruptibly().
Returns the condition instance bound to this lock instance. Only when the current thread obtains the lock can it call the await () method of the condition instance and release the lock.
As the name suggests, reentrantlock is a reentrant lock. I have involved some knowledge about this reentrant lock before. I will integrate it here and add it a little.
Reentrantlock is located in Java util. Under concurrent (j.u.c) package, it is the implementation class of lock interface. The basic usage is similar to synchronized. Both have reentrant and mutually exclusive features, but have extended functions.
Renntrantlock recommends the following basic wording:
class X {
//定义锁对象
private final reentrantlock lock = new reentrantlock();
// ...
//定义需要保证线程安全的方法
public void m() {
//加锁
lock.lock();
try{
// 保证线程安全的代码
}
// 使用finally块保证释放锁
finally {
lock.unlock()
}
}
}
1. API level locks
Reentrantlock is expressed as a mutex at the API level, which is completed through the lock () and unlock () methods. It is explicit, while synchronized is expressed as a mutex at the native syntax level, which is implicit.
2. Reentrant
Reentrant means that any thread can acquire the lock again after acquiring the lock without being blocked by the lock. Both synchronized and reentrant are reentrant, implicit and explicit.
Two key parts need to be solved to realize reentry:
3. Fair
As for the lock fairness part, the official document describes it like this (I won't post it in English). The vocabulary is relatively simple. I'll try to translate it:
The constructor of the reentrant class accepts an optional fairness parameter fair. There are two options:
The overall throughput of fair locks is often lower than that of non fair locks, that is, slower.
The fairness of lock does not guarantee the fairness of thread scheduling, but fair lock can reduce the probability of "hunger".
It should be noted that the irregular trylock() method does not support fairness settings. If the lock is available, it will successfully acquire the lock even if other threads wait longer than it.
4. Wait for interruptible
When the holding thread does not release the lock for a long time, the waiting thread can choose to give up waiting or deal with other things.
5. Lock binding
A reentrantlock object can bind multiple condition objects at the same time through newcondition().
JDK1. Before 6, reentrantlock was ahead of synchronized locks in performance, but jdk1 6 and later versions implement various lock optimization technologies. For reference: talk about concurrent Java SE1 For synchronized in 6, subsequent performance improvements will be more inclined to native synchronized.
Reference: in depth understanding of Java virtual machine Zhou Zhiming's art of Java Concurrent Programming Fang Tengfei