四、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来判断是否持有锁是错误的,除非你能保证程序中只会有一个线程来持有该锁。

 

转载于:https://www.cnblogs.com/lay2017/p/10264109.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值