BalanceAction generateCandidate(BalancerClusterState cluster, boolean isWeighing,
    boolean isForced) {
    if (cluster.getMaxReplicas() < cluster.numRacks) {
      LOG.trace("Skipping replica distribution as there are not enough racks to distribute them.");
      return BalanceAction.NULL_ACTION;
    }

    // Iterate through shuffled servers to find colocated replicas
    boolean foundColocatedReplicas = false;
    List<MoveRegionAction> moveRegionActions = new ArrayList<>();
    List<Integer> shuffledServerIndices = cluster.getShuffledServerIndices();
    for (int sourceIndex : shuffledServerIndices) {
      if (moveRegionActions.size() >= BATCH_SIZE || cluster.isStopRequested()) {
        break;
      }
      int[] serverRegions = cluster.regionsPerServer[sourceIndex];
      Set<ReplicaKey> replicaKeys = new HashSet<>(serverRegions.length);
      for (int regionIndex : serverRegions) {
        ReplicaKey replicaKey = getReplicaKey(cluster.regions[regionIndex]);
        if (replicaKeys.contains(replicaKey)) {
          foundColocatedReplicas = true;
          if (isWeighing) {
            // If weighing, fast exit with an actionable move
            return getAction(sourceIndex, regionIndex, pickOtherRandomServer(cluster, sourceIndex),
              -1);
          }
          // If not weighing, pick a good move
          for (int i = 0; i < cluster.numServers; i++) {
            // Randomize destination ordering so we aren't overloading one destination
            int destinationIndex = pickOtherRandomServer(cluster, sourceIndex);
            if (destinationIndex == sourceIndex) {
              continue;
            }
            MoveRegionAction possibleAction =
              new MoveRegionAction(regionIndex, sourceIndex, destinationIndex);
            if (isForced) {
              return possibleAction;
            }
            if (willBeAccepted(cluster, possibleAction)) {
              cluster.doAction(possibleAction); // Update cluster state to reflect move
              moveRegionActions.add(possibleAction);
              break;
            }
          }
        } else {
          replicaKeys.add(replicaKey);
        }
      }
    }

    if (!moveRegionActions.isEmpty()) {
      return batchMovesAndResetClusterState(cluster, moveRegionActions);
    }
    // If no colocated replicas are found, return NULL_ACTION
    if (foundColocatedReplicas) {
      LOG.warn("Could not find a place to put a colocated replica! We will force a move.");
      return generateCandidate(cluster, isWeighing, true);
    }
    LOG.trace("No colocated replicas found. No balancing action required.");
    return BalanceAction.NULL_ACTION;
  }
CandidateGenerator to distribute colocated replicas across different servers.
hbase-balancer/src/main/java/org/apache/hadoop/hbase/master/balancer/DistributeReplicasCandidateGenerator.java