public class RedisLock extends Object implements Lock, Serializable
Distributes lock based redis(unlock使用redis lua script)
可重入锁的一般场景:当前线程多次调用含有锁操作的函数、当前线程含有锁操作的函数自身调用
待完善:
1、获取锁成功的线程 A 定时续期锁:WatchDog
2、获取锁失败的线程 B 阻塞等待并监听(订阅)事件:subscribe
3、线程 A 释放锁时发送消息事件通知等待锁的线程B:publish
RedisLockFactory factory = new RedisLockFactory(redisTemplate);
class X {
public void m() {
Lock lock = factory.create("lockKey", 3000);
lock.lock(); // block until acquire lock or timeout
try {
// ... method body
} finally {
lock.unlock()
}
}
}
class Y {
public void m() {
Lock lock = factory.create("lockKey", 3000);
if (!lock.tryLock()) return;
try {
// ... method body
} finally {
lock.unlock();
}
}
}
class Z {
public void m() {
Lock lock = factory.create("lockKey", 3000);
// auto timeout release lock
if (!lock.tryLock(100, TimeUnit.MILLISECONDS)) return;
try {
// ... method body
} finally {
lock.unlock();
}
}
}
| 限定符和类型 | 方法和说明 |
|---|---|
void |
forceUnlock()
Force unlock
|
boolean |
isHeldByCurrentThread()
当前线程是否持有锁
{@code
class X {
Lock lock = new RedisLock(redisTemplate, "lockKey", 100);
// ...
|
boolean |
isLocked()
是否已锁(任何线程)
|
void |
lock()
等待锁直到获取(non interrupt)
|
void |
lockInterruptibly()
等待锁直到获取成功或抛出InterruptedException异常
|
Condition |
newCondition() |
boolean |
tryLock()
尝试获取锁,成功返回true,失败返回false
|
boolean |
tryLock(long timeout,
TimeUnit unit)
尝试获取锁,成功返回true,失败返回false
线程中断则抛出interrupted异常 |
void |
unlock()
释放锁
|
public void lockInterruptibly()
throws InterruptedException
lockInterruptibly 在接口中 LockInterruptedException - if call Thread#interruptpublic boolean tryLock()
public boolean tryLock(long timeout,
TimeUnit unit)
throws InterruptedException
tryLock 在接口中 Locktimeout - the timeout valueunit - the timeout unittrue lock successfullyInterruptedException - if interruptedpublic Condition newCondition()
newCondition 在接口中 Lockpublic boolean isHeldByCurrentThread()
class X {
Lock lock = new RedisLock(redisTemplate, "lockKey", 100);
// ...
public void m() {
assert !lock.isHeldByCurrentThread();
lock.lock();
try {
// ... method body
} finally {
lock.unlock();
}
}
}
true the current thread held lockedpublic boolean isLocked()
true is lockedpublic void forceUnlock()
Copyright © 2025. All rights reserved.