Database Reference
In-Depth Information
When the getChildren calls return their results, they use a callback
method, processResult , defined in the ChildrenCallback
interface. In this example, the method calls isLeader with the array of
child nodes to check to see if it is first in the list. If that is the case, it
updates its leader status and notifies any threads that might be waiting
for leadership to be obtained that the leader status might have changed:
public void processResult( int rc,
String path, Object ctx,
List<String> children) {
synchronized (lock) {
leader = isLeader(children);
System. out .println(node+" leader? "+leader);
lock.notify();
}
}
When ZooKeeper returns a list of children, it does not guarantee any
sort of ordering for the elements. To find out if the node is the leader,
which is defined as having the smallest node sequence, the list first has
to be sorted. Then the first element can be checked against the node
name:
protected boolean isLeader(List<String> children) {
if (children.size() == 0) return false ;
Collections. sort (children);
System. out .println(path+"/"+children.get(0)
+" should become leader. I am "+node);
return (node.equals(path+"/"+children.get(0)));
}
Notice that the getChildren response does not include the full path.
That has to be added during the comparison because the create
method does return the full path.
A server waiting to become leader calls the isLeader method without
any arguments in a loop. If the node is currently the leader, the method
Search WWH ::




Custom Search