在分布式锁的实现中,有一个比较重要的问题就是误解锁的问题,如何有效的避免A线程加的锁被B线程给解锁是非常重要的。
Redisson作为一个分布式锁用的比较多的框架,他是如何实现的这个功能呢?我们通过源码来深入展开介绍一下。
以下是 lock 方法,也就是加锁的入口,
@Override
public void lock(long leaseTime, TimeUnit unit) {
try {
lock(leaseTime, unit, false);
} catch (InterruptedException e) {
throw new IllegalStateException();
}
}
这里调用了一个<font style="color:#080808;background-color:#ffffff;">lock(long leaseTime, TimeUnit unit, boolean interruptibly) </font>
方法,放方法的大致内容是:
private void lock(long leaseTime, TimeUnit unit, boolean interruptibly) throws InterruptedException {
long threadId = Thread.currentThread().getId();
Long ttl = tryAcquire(-1, leaseTime, unit, threadId);
}