Database Reference
In-Depth Information
quickly returns
true
and the server can continue processing. If it is not
the leader, the calling thread waits on the lock object until it has been
notified by
processResult
or because the server has lost its
connection to ZooKeeper:
public boolean
isLeader() {
if
(leader && connected) {
System.
out
.println(node+" is the leader.");
return
leader;
}
System.
out
.println("Waiting for a change in the
lock.");
synchronized
(lock) {
try
{
lock.wait();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
return
leader && connected;
}
To see the example in action, a server is needed. This server does not do
anything except announce that it is “processing” something in a loop
while it has leadership. However, it is slightly unreliable, and 30
percent of the time it crashes, relinquishing its leadership position. If it
loses leadership without crashing, it goes back to waiting for leadership.
If it has lost connection, it exits entirely:
public class
UnreliableServer
implements
Runnable {
String name;
LeaderElection election;
public
UnreliableServer(String name,String
connect,String path)
throws
IOException {
this
.name = name;
election =
new
LeaderElection(connect,path);