1. The difference between fair lock and unfair lock
There is a difference between a fair lock and an unfair lock when it first seizes resources . When a fair lock first seizes resources, it will determine whether there are nodes in the CHL queue . If there are nodes on the queue, the current thread will definitely queue up on the CHL; unfair locks will directly compete for resources regardless of whether there are nodes on the CHL queue. It may cause nodes on the CHL queue to never obtain a lock, so it is called an unfair lock.
1.1 The lock method of unfair locks
1.2 The unlock method of unfair locks
2. Overview of reentrant locks
ReentrantLock is an unfair lock. Assuming that the thread currently holding the lock is thread A, there are thread B, thread C, ..., thread N in the CHL queue, and when thread A competes for resources again, it can directly obtain the lock. That is, when the thread that needs to acquire the lock and the thread currently holding the lock are the same, the lock can be acquired directly without queuing.
Three, practice
RLock lock = redisson.getLock("anyLock");
// 最常见的使用方法
lock.lock();
or
// 加锁以后10秒钟自动解锁
// 无需调用unlock方法手动解锁
RLock lock = redisson.getLock("anyLock");
lock.lock(10, TimeUnit.SECONDS);
// 尝试加锁,最多等待100秒,上锁以后10秒自动解锁
boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
if (res) {
try {
...
} finally {
lock.unlock();
}
}
or
RLock lock = redisson.getLock("anyLock");
lock.lockAsync();
lock.lockAsync(10, TimeUnit.SECONDS);
Future<Boolean> res = lock.tryLockAsync(100, 10, TimeUnit.SECONDS);
Four, summary
The RLock object fully complies with the Java Lock specification. That is to say, only the process with the lock can be unlocked, and other processes will throw an IllegalMonitorStateException error when unlocking . But if you encounter a situation that requires other processes to be able to unlock , please use the distributed semaphore Semaphore object.