九、curator recipes之不可重入锁InterProcessSemaphoreMutex

本文深入探讨了recipes的InterProcessSemaphoreMutex,一种不可重入的互斥锁,详细解释了其工作原理,如何避免死锁,以及在多线程环境下使用时的注意事项。通过具体的Java代码示例,演示了如何在实际项目中应用这种锁。

简介

recipes的InterProcessSemaphoreMutex是一种不可重入的互斥锁,也就意味着即使是同一个线程也无法在持有锁的情况下再次获得锁,所以需要注意,不可重入的锁很容易在一些情况导致死锁,比如你写了一个递归。

官方文档:http://curator.apache.org/curator-recipes/shared-lock.html

javaDoc:http://curator.apache.org/curator-recipes/shared-lock.html

代码示例

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class SemaphoreMutexDemo {
    private static CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(3000, 3));
    private static String path = "/locks/semaphore/0001";
    static {
        client.start();
    }

    public static void main(String[] args) throws Exception {
        startThread0();
        Thread.sleep(10);
        startThread1();
        Thread.sleep(50000);
        client.close();
    }

    private static void startThread0() {
        new Thread(() -> {
            InterProcessSemaphoreMutex lock = new InterProcessSemaphoreMutex(client, path);
            try {
                System.out.println("thread0 acquiring");
                lock.acquire();
                System.out.println("thread0 acquired");
                System.out.println("thread0 sleep for 3s");
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    lock.release();
                    System.out.println("thread0 release");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private static void startThread1() {
        new Thread(() -> {
            InterProcessSemaphoreMutex lock = new InterProcessSemaphoreMutex(client, path);
            try {
                System.out.println("thread1 acquiring");
                lock.acquire();
                System.out.println("thread1 acquired");
                System.out.println("thread1 sleep for 3s");
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    lock.release();
                    System.out.println("thread1 release");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值