package io.github.azyet;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
/**
* Hello world!
*/
public class ZKBarrier extends SyncPrimitive {
String root;
private String name;
private int size;
/**
* ****** Barrier constructor
* ******
* ****** @param address
* ****** @param name
* ****** @param size
*******/
ZKBarrier(String address, String rootNode, int size)
throws KeeperException, InterruptedException, IOException {
super(address);
this.root = rootNode;
this.size = size;
// Create barrier node
if (zk != null) {
Stat s = zk.exists(this.root, false);
if (s == null) {
zk.create(this.root, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
}
// My node name
name = new String(InetAddress.getLocalHost().getCanonicalHostName().toString());
}
boolean enter() throws KeeperException, InterruptedException {
zk.create(root + "/" + name, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL);
while (true) {
synchronized (mutex) {
List<String> list = zk.getChildren(root, true);
System.out.print(list.size()+" children: ");
for (String s : list) {
System.out.print(s+" ");
}
System.out.print("\n");
if (list.size() < size) {
mutex.wait();
} else {
System.out.println("time to work!!!");
return true;
}
}
}
}
/**
* ****** Wait until all reach barrier
* ******
* ****** @return
* ****** @throws KeeperException
* ****** @throws InterruptedException
*******/
boolean leave() throws KeeperException, InterruptedException {
zk.delete(root + "/" + name, 0);
while (true) {
synchronized (mutex) {
ArrayList<String> list = (ArrayList<String>) zk.getChildren(root, true);
if (list.size() > 0) {
System.out.print(list.size()+" children: ");
for (String s : list) {
System.out.print(s + " ");
}
Thread.sleep(1000);
System.out.print("\n");
mutex.wait();
} else {
return true;
}
}
}
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("input node name");
return;
}
try {
ZKBarrier zkBarrier = new ZKBarrier("dell:2181", "/testRoot3", 3);
//purge the children under testrRoot
zkBarrier.name = args[0];
System.out.println("Entering the Barrier");
zkBarrier.enter();
System.out.println("Work done, leaving");
zkBarrier.leave();
return;
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}