Database Reference
In-Depth Information
When the
main()
method is run, it creates a
CreateGroup
instance and then calls its
connect()
method. This method instantiates a new
ZooKeeper
object, which is the
central class of the client API and the one that maintains the connection between the client
and the ZooKeeper service. The constructor takes three arguments: the first is the host ad-
is the session timeout in milliseconds (which we set to 5 seconds), explained in more de-
tail later; and the third is an instance of a
Watcher
object. The
Watcher
object receives
callbacks from ZooKeeper to inform it of various events. In this scenario,
CreateGroup
is a
Watcher
, so we pass this to the
ZooKeeper
constructor.
When a
ZooKeeper
instance is created, it starts a thread to connect to the ZooKeeper
service. The call to the constructor returns immediately, so it is important to wait for the
connection to be established before using the
ZooKeeper
object. We make use of Java's
CountDownLatch
class (in the
java.util.concurrent
package) to block until
the
ZooKeeper
instance is ready. This is where the
Watcher
comes in. The
Watcher
interface has a single method:
public
void
process
(
WatchedEvent event
);
When the client has connected to ZooKeeper, the
Watcher
receives a call to its
pro-
cess()
method with an event indicating that it has connected. On receiving a connection
event (represented by the
Watcher.Event.KeeperState
enum, with value
Syn-
cConnected
), we decrement the counter in the
CountDownLatch
, using its
coun-
tDown()
method. The latch was created with a count of one, representing the number of
events that need to occur before it releases all waiting threads. After calling
coun-
tDown()
once, the counter reaches zero and the
await()
method returns.
The
connect()
method has now returned, and the next method to be invoked on the
CreateGroup
is the
create()
method. In this method, we create a new ZooKeeper
znode using the
create()
method on the
ZooKeeper
instance. The arguments it takes
are the path (represented by a string), the contents of the znode (a byte array
null
here),
an access control list (or ACL for short, which here is completely open, allowing any cli-
ent to read from or write to the znode), and the nature of the znode to be created.
Znodes may be ephemeral or persistent. An ephemeral znode will be deleted by the
ZooKeeper service when the client that created it disconnects, either explicitly or because
the client terminates for whatever reason. A persistent znode, on the other hand, is not de-
leted when the client disconnects. We want the znode representing a group to live longer
than the lifetime of the program that creates it, so we create a persistent znode.