Curator使用:(六)分布式计数器

分布式计数器介绍##

和分布式锁类似,下面是实现分布式计数器的功能

代码###

    //分布式计数器
    DistributedAtomicInteger atomicInteger = new DistributedAtomicInteger(cc,"/distributed_atomic_counter",new ExponentialBackoffRetry(1000,3));
    AtomicValue av = atomicInteger.add(10);
    System.out.println(av.succeeded());//true
    System.out.println(av.preValue());//0
    System.out.println(av.postValue());//10

每个DistributedAtomicXXX里面都有一个AtomicValue,这个是分布式的核心实现类。

    AtomicValue<byte[]>   trySet(MakeValue makeValue) throws Exception
    {
        MutableAtomicValue<byte[]>  result = new MutableAtomicValue<byte[]>(null, null, false);
        //尝试下乐观锁
        tryOptimistic(result, makeValue);
        if ( !result.succeeded() && (mutex != null) )
        {
            //失败的话再使用排他锁
            tryWithMutex(result, makeValue);
        }

        return result;
    }

原文地址:https://www.cnblogs.com/june777/p/11881340.html