[ZooKeeper]纠正官网的Barrier的示例

原创 2016年06月01日 18:39:37

Barrier接口

public interface Barrier {  
  
    String enter() throws InterruptedException, BarrierException;  
      
    void leave(String path) throws InterruptedException, BarrierException;  
} 


单机版的Barrier两个CountDownLatch就可以实现

import java.util.concurrent.CountDownLatch;

/** 
 * 单机模式的Barrier 
 */  
public class StandaloneBarrier implements Barrier {  
      
    private CountDownLatch startSignal;  
      
    private CountDownLatch stopSignal;  
      
    public StandaloneBarrier(int count) {  
        this.startSignal = new CountDownLatch(count);  
        this.stopSignal = new CountDownLatch(count);  
    }  
  
    @Override  
    public String enter() throws InterruptedException {  
        startSignal.countDown();  
        startSignal.await();  
        return "success";
    }  
  
    @Override  
    public void leave(String path) throws InterruptedException {  
        stopSignal.countDown();  
        stopSignal.await();  
    }  
  
}


分布式版的Barrier,纠正了leave方法里SEQUENTIAL节点删除失败的问题

import java.io.IOException;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * 分布式Barrier
 */
public class DistributedBarrier implements Barrier, Watcher {
    
    private String root;
    
    private String barrierName;
    
    private int count;
    
    private ZooKeeper zooKeeper;
    
    private Lock lock;
    
    private Condition nodeChildrenChange;
    
    private volatile boolean expired;
    
    public DistributedBarrier(String address, String root, String barrierName, int count) throws BarrierException, InterruptedException {
        this.root = root;
        this.barrierName = barrierName;
        this.count = count;
        
        try {
            zooKeeper = new ZooKeeper(address, 3000, this);
            
            lock = new ReentrantLock();
            nodeChildrenChange = lock.newCondition();
        } catch (IOException e) {
            throw new BarrierException(e);
        }
        
        try {
            Stat stat = zooKeeper.exists(root, false);
            if (stat == null) {
                zooKeeper.create(root, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (KeeperException e) {
            if (e.code() != Code.NODEEXISTS) {
                throw new BarrierException(e);
            }
        }
    }

    @Override
    public String enter() throws InterruptedException, BarrierException {
        try {
            String actualPath  = zooKeeper.create(root + "/" + barrierName, new byte[0], 
                    Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            while (!Thread.interrupted() && !expired) {
                List<String> list = zooKeeper.getChildren(root, true);
                if (list.size() < count) {
                    lock.lock();
                    try {
                        nodeChildrenChange.await();
                    } finally {
                        lock.unlock();
                    }
                } else {
                    return actualPath;
                }
            }
            throw new BarrierException("interruped or expired");
        } catch (KeeperException e) {
            throw new BarrierException(e);
        }
    }

    @Override
    public void leave(String path) throws InterruptedException, BarrierException {
        try {
            zooKeeper.delete(path, 0);
            while (!Thread.interrupted() && !expired) {
                List<String> list = zooKeeper.getChildren(root, true);
                if (!list.isEmpty()) {
                    lock.lock();
                    try {
                        nodeChildrenChange.await();
                    } finally {
                        lock.unlock();
                    }
                }
            }
            throw new BarrierException("interruped or expired");
        } catch (KeeperException e) {
            throw new BarrierException(e);
        }
    }

    @Override
    public void process(WatchedEvent event) {
        if (event.getType() == Watcher.Event.EventType.None) {
            if (event.getState() == Watcher.Event.KeeperState.Expired) {
                expired = true;
                try {
                    zooKeeper.close();
                } catch (InterruptedException e) {
                    // do nothing;
                }
            }
        } else if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
            lock.lock();
            try {
                nodeChildrenChange.signalAll();
            } finally {
                lock.unlock();
            }
        }
    }

}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Zookeeper 编程指南官网文档学习笔记

Zookeeper 编程指南官网文档学习笔记此文是link zk program guide的阅读笔记。 由于对原文中出现的watches还没有很好的理解,在翻译时结合了上下文和自己的理解有时翻译成...

NGUI官网示例13 –Character角色装配与储物箱(四)

选择Shoulders对象,为其添加一个EquipmentSlot(Component->NGUI->Example-> EquipmentSlot),并把shoulders中的各个子对象赋值给该组件...

phonegap 开发入门 PhoneGap官方网站上有详细的入门示例教程,这里,我针对使用PhoneGap进行Android移动应用的开发对其官网的Get Started进行一些介绍、补充。 Ste

phonegap 开发入门 PhoneGap官方网站上有详细的入门示例教程,这里,我针对使用PhoneGap进行Android移动应用的开发对其官网的Get Started进行一些介绍、补充。 ...

NGUI官网示例8 – Scroll View(Camera)

http://game.ceeger.com/forum/read.php?tid=4298 NGUI官网示例--讲解:http://game.ceeger.com/forum/read...

RabbitMQ官网示例分析

官网地址 http://www.rabbitmq.com/maven 地址 (发布端和消费端maven依赖在一起) The snippet below can be copied and past...

Android 7.0 示例(官网)

通过下面的代码示例,了解 Android 7.0 功能和 API。要在 Android Studio 中下载示例,请选择 File > New > Import Sample 菜单选项。 注:这...

NGUI官网示例11 –Drag ; Drop(图标与物体拖拽放置)(二)

为ListPanel创建一个空的游戏对象,并命名为DragDropContainer,reset一下,并为它添加一个Collider(NGUI->Attach a collider),如图所示 ...

NGUI官网示例13 –Character角色装配与储物箱(三)

该部分主要是为实现装备在拖动的时候出现拖动图标的效果和当鼠标放置在装备上时提示装备的一些信息而做准备。 使用UI Tool创建一个Simple 2D UI层级结构,其Layer为2DGUI,我们通过...

NGUI官网示例7-- ScrollView讲解(三)

这里官方例子中的最下角,有两个元件,一个是用于控制item中心显示的check box,还有一个是实现窗口旋转的功能。还有右上角的Logo图标,鼠标点击它是会自动弹出来,鼠标移开后又会自动弹回原位。现...

NGUI官网示例8 – Scroll View(Camera)

在上一个示例中的ScrollView使用到了Shader的处理,而对于一些低端的机器或者移动设备可能会出现显示不正常的结果,所以,NGUI还为我们准备了另外一个处理方式,也就是通过摄像机的移动来达到同...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)