Curator
是ZooKeeper
的一个客户端框架,其中封装了分布式互斥锁
的实现,最为常用的是InterProcessMutex
,本文将对其进行代码剖析
简介
InterProcessMutex
基于Zookeeper
实现了分布式的公平可重入互斥锁
,类似于单个JVM进程内的ReentrantLock(fair=true)
构造函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
|
获取锁
InterProcessMutex.acquire
InterProcessMutex.internalLock
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
private boolean internalLock(long time, TimeUnit unit) throws Exception{ Thread currentThread = Thread.currentThread(); LockData lockData = threadData.get(currentThread); if ( lockData != null ){
|
LockInternals.attemptLock
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
|
LockInternals.internalLockLoop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
|
释放锁
弄明白了获取锁的原理,释放锁的逻辑就很清晰了
InterProcessMutex.release
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
public void release() throws Exception{ Thread currentThread = Thread.currentThread(); LockData lockData = threadData.get(currentThread); if ( lockData == null ){
|
LockInternals.releaseLock
1 2 3 4 5
|
void releaseLock(String lockPath) throws Exception{ revocable.set(null);
|
总结
InterProcessMutex
的特性
- 分布式锁(基于
Zookeeper
)
- 互斥锁
- 公平锁(
监听上一临时顺序节点
+ wait() / notifyAll()
)
- 可重入