说明

完全分布的全局同步锁,意味着任何时间的快照,没有两个客户端认为它们拥有相同的锁。 注意:与InterProcessMutex不同,此锁不可重入。

参与类

  • InterProcessSemaphoreMutex

用法

创建一个InterProcessSemaphoreMutex

public InterProcessSemaphoreMutex(CuratorFramework client,
                         String path)
Parameters:
client - client
path - the path to lock

一般用法

要获取锁,请使用以下方法之一:

public void acquire()
Acquire the mutex - blocking until it's available. Must be balanced by a call to release().
public boolean acquire(long time,
                       TimeUnit unit)
Acquire the mutex - blocks until it's available or the given time expires. Must be balanced by a call to release().
     
Parameters:
time - time to wait
unit - time unit
Returns:
true if the mutex was acquired, false if not

要释放互斥量,请调用:

public void release()
Perform one release of the mutex if the calling thread is the same thread that acquired it.

错误处理

强烈建议您添加一个ConnectionStateListener并观察SUSPENDED和LOST状态更改。 如果报告了SUSPENDED状态,则无法确定您仍然保持锁定状态,除非您随后收到RECONNECTED状态。 如果报告了LOST状态,则确定您不再持有该锁。