服务注册与分布式协调 / 系统课时
可重入分布式锁
可重入分布式锁
本课使用 Curator InterProcessMutex 对跨进程临界区加锁,并验证同一线程可以重复获取、其他线程会等待或超时。完成后,你能够正确组织获取、执行业务和释放锁的代码结构。
学习目标
- 使用
InterProcessMutex获取和释放分布式锁 - 理解可重入计数、超时获取和所有权约束
- 处理异常、会话丢失和临界区幂等
锁的工作方式
InterProcessMutex 使用临时顺序节点排队。序号最小的参与者进入临界区,其他参与者监听前驱节点;持有者释放锁或会话失效后,后继参与者继续竞争。
同一线程对同一个锁对象可重复获取,每次获取都会增加重入计数,因此必须按相同次数释放。锁不能由未持有它的线程释放。
可运行示例
下面示例用 TestingServer 创建临时 ZooKeeper。主线程连续获取两次锁,另一个线程在 500 毫秒内无法获得同一路径的锁,随后主线程按两次释放。
java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.test.TestingServer;
public class ReentrantLockDemo {
public static void main(String[] args) throws Exception {
try (TestingServer server = new TestingServer();
CuratorFramework client = CuratorFrameworkFactory.newClient(
server.getConnectString(), new RetryOneTime(200))) {
client.start();
client.blockUntilConnected();
InterProcessMutex mainLock =
new InterProcessMutex(client, "/locks/report");
mainLock.acquire();
mainLock.acquire();
System.out.println("mainReentrant=true");
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
Future<Boolean> result = pool.submit(() -> {
InterProcessMutex otherLock =
new InterProcessMutex(client, "/locks/report");
boolean acquired =
otherLock.acquire(500, TimeUnit.MILLISECONDS);
if (acquired) {
otherLock.release();
}
return acquired;
});
System.out.println("otherAcquired=" + result.get());
} finally {
// 重入两次就必须释放两次。
mainLock.release();
mainLock.release();
pool.shutdownNow();
}
}
}
}预期输出:
text
mainReentrant=true
otherAcquired=false生产代码结构
实际业务应优先使用带超时的 acquire,避免请求线程无限等待。释放必须放在 finally 中,并用布尔变量记录是否真正获得锁。
java
boolean acquired = false;
try {
acquired = lock.acquire(3, TimeUnit.SECONDS);
if (!acquired) {
throw new IllegalStateException("获取分布式锁超时");
}
executeIdempotentBusiness();
} finally {
if (acquired && lock.isOwnedByCurrentThread()) {
lock.release();
}
}这是片段示例,依赖已启动的 CuratorFramework client、InterProcessMutex lock 和业务方法 executeIdempotentBusiness()。生效行为是:只有成功持锁的当前线程才进入业务,并且只由持锁线程执行释放。
会话丢失不是正常解锁
连接短暂断开时锁节点可能仍存在,但会话一旦进入 LOST,临时节点会被删除,其他参与者可能获得锁。原持有者即使仍在执行,也不再拥有排他性,因此临界区必须可中止,或使用业务版本号、租约令牌等方式阻止过期持有者提交结果。
本课总结
InterProcessMutex支持跨进程互斥和同一线程可重入- 获取几次就必须释放几次,释放动作应放在
finally - 会话丢失后锁所有权失效,业务仍需幂等和过期持有者隔离
下一课预告
下一课将扩展到 InterProcessReadWriteLock 和 InterProcessMultiLock,并分析多资源加锁的顺序与死锁风险。
按自己的节奏,确认真正理解。