public void waitToBecomeLeader() {
    while (!candidate.isStopped()) {
      try {
        if (ZKUtil.createEphemeralNodeAndWatch(watcher, leaderZNode, nodeId)) {
          // claimed the leader znode
          leaderExists.set(true);
          if (LOG.isDebugEnabled()) {
            LOG.debug("Claimed the leader znode as '" + Bytes.toStringBinary(nodeId) + "'");
          }
          return;
        }

        // if claiming the node failed, there should be another existing node
        byte[] currentId = ZKUtil.getDataAndWatch(watcher, leaderZNode);
        if (currentId != null && Bytes.equals(currentId, nodeId)) {
          // claimed with our ID, but we didn't grab it, possibly restarted?
          LOG.info(
            "Found existing leader with our ID (" + Bytes.toStringBinary(nodeId) + "), removing");
          ZKUtil.deleteNode(watcher, leaderZNode);
          leaderExists.set(false);
        } else {
          LOG.info("Found existing leader with ID: {}", Bytes.toStringBinary(currentId));
          leaderExists.set(true);
        }
      } catch (KeeperException ke) {
        watcher.abort("Unexpected error from ZK, stopping candidate", ke);
        candidate.stop("Unexpected error from ZK: " + ke.getMessage());
        return;
      }

      // wait for next chance
      synchronized (lock) {
        while (leaderExists.get() && !candidate.isStopped()) {
          try {
            lock.wait();
          } catch (InterruptedException ie) {
            LOG.debug("Interrupted waiting on leader", ie);
          }
        }
      }
    }
  }
Blocks until this instance has claimed the leader ZNode in ZooKeeper
hbase-zookeeper/src/main/java/org/apache/hadoop/hbase/zookeeper/ZKLeaderManager.java