Database Reference
In-Depth Information
their names. If a child contains its identifier, it knows that the create operation suc-
ceeded, and it shouldn't create another child znode. If no child has the identifier in its
name, the client can safely create a new sequential child znode.
The client's session identifier is a long integer that is unique for the ZooKeeper service
and therefore ideal for the purpose of identifying a client across connection loss events.
The session identifier can be obtained by calling the getSessionId() method on the
ZooKeeper Java class.
The ephemeral sequential znode should be created with a name of the form lock- <ses-
sionId> - , so that when the sequence number is appended by ZooKeeper, the name be-
comes lock- <sessionId> - <sequenceNumber> . The sequence numbers are unique
to the parent, not to the name of the child, so this technique allows the child znodes to
identify their creators as well as impose an order of creation.
Unrecoverable exceptions
If a client's ZooKeeper session expires, the ephemeral znode created by the client will be
deleted, effectively relinquishing the lock (or at least forfeiting the client's turn to acquire
the lock). The application using the lock should realize that it no longer holds the lock,
clean up its state, and then start again by creating a new lock object and trying to acquire
it. Notice that it is the application that controls this process, not the lock implementation,
since it cannot second-guess how the application needs to clean up its state.
Implementation
Accounting for all of the failure modes is nontrivial, so implementing a distributed lock
correctly is a delicate matter. ZooKeeper comes with a production-quality lock imple-
mentation in Java called WriteLock that is very easy for clients to use.
More Distributed Data Structures and Protocols
There are many distributed data structures and protocols that can be built with ZooKeeper,
such as barriers, queues, and two-phase commit. One interesting thing to note is that these
are synchronous protocols, even though we use asynchronous ZooKeeper primitives (such
as notifications) to build them.
The ZooKeeper website describes several such data structures and protocols in pseudo-
code. ZooKeeper comes with implementations of some of these standard recipes (includ-
ing locks, leader election, and queues); they can be found in the recipes directory of the
distribution.
Search WWH ::




Custom Search