1、描述
共享锁:全局同步分布式锁,同一时间两台机器只能有一台获得锁
2、参与类
InterProcessMutex
3、用法
3.1 创建 InterProcessMutex 实例
public InterProcessMutex(CuratorFramework client, String path) Parameters: client - client path - the path to lock
3.2 一般用法
用其中一个方法,获取锁
public void acquire() Acquire the mutex - blocking until it‘s available. Note: the same thread can call acquire re-entrantly. Each call to acquire must be balanced by a call to release()
在锁可用之前会获取互斥锁会一直阻塞。注意:同一个线程可用调用 acquire 重新参与争抢锁资源.每次调用都要调 release() 平衡。
public boolean acquire(long time, TimeUnit unit) Acquire the mutex - blocks until it‘s available or the given time expires. Note: the same thread can call acquire re-entrantly. Each call to acquire that returns true 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
该方法在锁可用或者超时之前会阻塞. 返回 true 表示已获取到锁.
调用 release() 释放互斥体
public void release() Perform one release of the mutex if the calling thread is the same thread that acquired it. If the thread had made multiple calls to acquire, the mutex will still be held when this method returns.
如果是执行 acquired 操作的线程调用该方法会释放一个互斥体.但如果一个线程已经多次调用 acquired 操作,那当该方法返回时,互斥体会依然被保留。
NOTE: A InterProcessMutex instance is reusable. i.e. don‘t create a new instance every time. Re-use a single instance.
注意:InterProcessMutex 实例 是可重用的.不用每次都创建一个新的实例. 重用一个单实例.
4、撤销
InterProcessMutex supports a cooperative revocation mechanism as described on the ZooKeeper recipes wiki
InterProcessMutex支持可协商的撤回机制,正如在 ZK recipes 模块中描述的一样。
调用 makeRevocable 方法撤回互斥体
public void makeRevocable(RevocationListener<T> listener)
Make the lock revocable. Your listener will get called when another process/thread wants you to release the lock. Revocation is cooperative. Parameters: listener - the listener
使锁可撤销.当其他进程/线程想让你释放锁时,RevocationListener 监听器会被调用. 撤销是可协商的.
To ask for a lock to revoke/release, use the static method in the Revoker class:
让一个锁撤销/释放,可以使用 Revoker 类中的静态方法
public static void attemptRevoke(CuratorFramework client, String path) throws Exception
Utility to mark a lock for revocation. Assuming that the lock has been registered with a RevocationListener, it will get called and the lock should be released. Note, however, that revocation is cooperative. Parameters: client - the client path - the path of the lock - usually from something like InterProcessMutex.getParticipantNodes()
标记锁撤回的作用.如果锁已经注册了 RevocationListener 监听器,这个方法就会被调用,锁也会被释放.
注意:不管怎样,撤销都是可协商的。
5 错误处理
It is strongly recommended that you add a ConnectionStateListener and watch for SUSPENDED and LOST state changes. If a SUSPENDED state is reported you cannot be certain that you still hold the lock unless you subsequently receive a RECONNECTED state. If a LOST state is reported it is certain that you no longer hold the lock.
强烈推荐使用 ConnectionStateListener 监听器 监视 SUSPENDED and LOST 状态改变. 如果 SUSPENDED 状态被报告 你没有看准的话 ,你会一直拥有这个锁除非你随后收到一个 RECONNECTED 状态. 如果 LOST 状态被报告 那可以确定你已经不再拥有这个锁了.
时间: 2024-10-11 22:03:41