十curator recipes之信号量InterProcessSemaphoreV2

Posted lay2017

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了十curator recipes之信号量InterProcessSemaphoreV2相关的知识,希望对你有一定的参考价值。

简介

跟Java并信号量没有什么不同,curator实现的信号量也是基于令牌桶算法,当一个线程要执行的时候就去桶里面获取令牌,如果有足够的令牌那么我就执行如果没有那么我就阻塞,当线程执行完毕也要将令牌放回桶里。

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

javaDoc:http://curator.apache.org/apidocs/org/apache/curator/framework/recipes/locks/InterProcessSemaphoreV2.html

代码示例

以下示例中,我们设置了信号量为1,如果其中一个线程取走了,那么下一个线程将阻塞直接信号量被返回到桶里面。

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

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

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

    private static void startThread1() {
        new Thread(() -> {
            InterProcessSemaphoreV2 semaphoreV2 = new InterProcessSemaphoreV2(client, path, 1);
            Lease lease = null;
            try {
                System.out.println("thread0 acquiring");
                lease = semaphoreV2.acquire();
                System.out.println("thread0 acquired and sleeping");
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                semaphoreV2.returnLease(lease);
                System.out.println("thread0 return lease");
            }
        }).start();
    }

    private static void startThread0() {
        new Thread(() -> {
            InterProcessSemaphoreV2 semaphoreV2 = new InterProcessSemaphoreV2(client, path, 1);
            Lease lease = null;
            try {
                System.out.println("thread1 acquiring");
                lease = semaphoreV2.acquire();
                System.out.println("thread1 acquired and sleeping");
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                semaphoreV2.returnLease(lease);
                System.out.println("thread1 return lease");
            }
        }).start();
    }
}

 

以上是关于十curator recipes之信号量InterProcessSemaphoreV2的主要内容,如果未能解决你的问题,请参考以下文章

十九curator recipes之PathChildrenCache

二十curator recipes之NodeCache

curator recipes之屏障barrier

七curator recipes之阻塞队列SimpleDistributedQueue

九curator recipes之不可重入锁InterProcessSemaphoreMutex

八curator recipes之选举主节点LeaderSelector