Database Reference
In-Depth Information
public
UnreliableLeader(String connect,String name) {
this
.connect = connect;
this
.name = name;
}
public void
stateChanged(CuratorFramework arg0,
ConnectionState arg1) {
if
(arg1 != ConnectionState.
CONNECTED
) leader =
false
;
}
public void
takeLeadership(CuratorFramework client)
throws
Exception {
leader =
true
;
Random rng =
new
Random();
while
(leader) {
if
(rng.nextDouble() < 0.30) {
System.
out
.println(name+": crashing");
return
;
}
System.
out
.println(name+": processing event");
Thread.
sleep
(rng.nextInt(1000));
}
}
}
The
LeaderLatch
client takes a different approach, offering a
hasLeadership
method to check to see if the server still has leadership
andan
await
methodtowaitforleadership.Usingthe
LeaderLatch
looks
something like this:
LeaderLatch latch = new LeaderLatch(client,"/
leader_queue");
latch.start();
latch.await();
while(latch.hasLeadership()) {
//Do work here
}