Database Reference
In-Depth Information
}
}
Example 21-3. A helper class that waits for the ZooKeeper connection to be established
public class
ConnectionWatcher
implements
Watcher
{
private static final
int
SESSION_TIMEOUT
=
5000
;
protected
ZooKeeper zk
;
private
CountDownLatch connectedSignal
=
new
CountDownLatch
(
1
);
public
void
connect
(
String hosts
)
throws
IOException
,
InterruptedException
{
zk
=
new
ZooKeeper
(
hosts
,
SESSION_TIMEOUT
,
this
);
connectedSignal
.
await
();
}
@Override
public
void
process
(
WatchedEvent event
) {
if
(
event
.
getState
() ==
KeeperState
.
SyncConnected
) {
connectedSignal
.
countDown
();
}
}
public
void
close
()
throws
InterruptedException
{
zk
.
close
();
}
}
The code for
JoinGroup
is very similar to
CreateGroup
. It creates an ephemeral
znode as a child of the group znode in its
join()
method, then simulates doing work of
some kind by sleeping until the process is forcibly terminated. Later, you will see that
upon termination, the ephemeral znode is removed by ZooKeeper.
Listing Members in a Group
Now we need a program to find the members in a group (see
Example 21-4
)
.
Example 21-4. A program to list the members in a group
public class
ListGroup
extends
ConnectionWatcher
{
public
void
list
(
String groupName
)
throws
KeeperException
,
InterruptedException
{
String path
=
"/"
+
groupName
;