四、curator recipes之共享重入互斥锁
简介
curator的recipes实现了可重入互斥锁,允许你在分布式场景下多个进程之间实现锁的互斥以协调多进程执行。
相关类:InterProcessMutex
官方文档:http://curator.apache.org/curator-recipes/shared-reentrant-lock.html
javaDoc:http://curator.apache.org/apidocs/org/apache/curator/framework/recipes/locks/InterProcessMutex.html
依赖
<dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>4.1.0</version> </dependency>
代码示例
以下代码,子线程先抢到了锁,而主线程进入阻塞。子线程5秒以后释放了锁,主线程这时候争抢到了锁,并最终释放锁。
对于互斥锁来说,只有一个线程能够持有,其它线程必须阻塞等待。
如果已经持有锁,又多次重入了,那么在释放的时候也得多次释放。
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.ExponentialBackoffRetry; public class MutexDemo { private static InterProcessMutex lock; private static CuratorFramework client; static { client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(3000, 3)); lock = new InterProcessMutex(client, "/locks/0001"); client.start(); System.out.println("started"); } public static void main(String[] args) throws Exception { new Thread(() -> { try { System.out.println("thread0 争抢锁"); lock.acquire(); System.out.println("thread0 抢到了锁,进入休眠"); Thread.sleep(5000); System.out.println("thread0 结束休眠"); } catch (Exception e) { e.printStackTrace(); } finally { try {
// 当前线程获取到了锁 if (lock.isOwnedByCurrentThread()) { lock.release(); } System.out.println("thread0 释放了锁"); } catch (Exception e) { e.printStackTrace(); } } }).start(); // 休眠10毫秒,让子线程争抢到锁 Thread.sleep(10); System.out.println("main 争抢锁"); lock.acquire(); System.out.println("main 抢到了锁"); lock.release(); System.out.println("main 释放了锁"); client.close(); } }
注意:这里使用了isOwnedByCurrentThread,如果当前线程持有该锁,那么返回true,否则返回false。
它与isAcquiredInThisProcess的区别在于,isAcquiredInThisProcess只要当前JVM中有一个线程持有该锁就会返回true。
所以,如果采用isAcquiredInThisProcess来判断是否持有锁是错误的,除非你能保证程序中只会有一个线程来持有该锁。