Database Reference
In-Depth Information
}
}
}
The code is careful not to retry
KeeperException.SessionExpiredException
,
because when a session expires, the
ZooKeeper
object enters the
CLOSED
state, from
which it can never reconnect (refer to
Figure 21-3
)
. We simply rethrow the exception
[
150
]
and let the caller create a new
ZooKeeper
instance, so that the whole
write()
method
can be retried. A simple way to create a new instance is to create a new
ConfigUp-
dater
(which we've actually renamed
ResilientConfigUpdater
) to recover from
an expired session:
public static
void
main
(
String
[]
args
)
throws
Exception
{
while
(
true
) {
try
{
ResilientConfigUpdater configUpdater
=
new
ResilientConfigUpdater
(
args
[
0
]);
configUpdater
.
run
();
}
catch
(
KeeperException
.
SessionExpiredException
e
) {
// start a new session
}
catch
(
KeeperException e
) {
// already retried, so exit
e
.
printStackTrace
();
break
;
}
}
}
An alternative way of dealing with session expiry would be to look for a
KeeperState
of type
Expired
in the watcher (that would be the
ConnectionWatcher
in the ex-
ample here), and create a new connection when this is detected. This way, we would just
keep retrying the
write()
method, even if we got a
KeeperExcep-
tion.SessionExpiredException
, since the connection should eventually be rees-
tablished. Regardless of the precise mechanics of how we recover from an expired ses-
sion, the important point is that it is a different kind of failure from connection loss and
needs to be handled differently.