ZooKeeper getZooKeeper() throws Exception {
    if (SessionFailRetryLoop.sessionForThreadHasFailed()) {
      throw new SessionFailRetryLoop.SessionFailedException();
    }

    Exception exception = backgroundExceptions.poll();
    if (exception != null) {
      log.error("Background exception caught", exception);
      tracer.get().addCount("background-exceptions", 1);
      throw exception;
    }

    boolean localIsConnected = isConnected.get();
    if (!localIsConnected) {
      checkTimeouts();
    }

    return zooKeeper.getZooKeeper();
  }