private synchronized void recalculateSelectedHosts()

in server/src/main/java/org/apache/cassandra/sidecar/cluster/driver/SidecarLoadBalancingPolicy.java [179:233]


    private synchronized void recalculateSelectedHosts()
    {
        Map<Boolean, List<Host>> partitionedHosts = allHosts.stream()
                                                            .collect(Collectors.partitioningBy(this::isLocalHost));
        List<Host> localHosts = partitionedHosts.get(true);
        int numLocalHostsConfigured = localHostAddresses.size();
        if (localHosts == null || localHosts.isEmpty())
        {
            LOGGER.warn("Did not find any local hosts in allHosts.");
        }
        else
        {
            if (localHosts.size() < numLocalHostsConfigured)
            {
                LOGGER.warn("Could not find all configured local hosts in host list. ConfiguredHosts={} AvailableHosts={}",
                            numLocalHostsConfigured, localHosts.size());
            }
            selectedHosts.addAll(localHosts);
        }
        int requiredNonLocalHosts = this.totalRequestedConnections - selectedHosts.size();
        if (requiredNonLocalHosts > 0)
        {
            List<Host> nonLocalHosts = partitionedHosts.get(false);
            if (nonLocalHosts == null || nonLocalHosts.isEmpty())
            {
                LOGGER.debug("Did not find any non-local hosts in allHosts");
                return;
            }

            // Remove down and already selected hosts from consideration
            nonLocalHosts = nonLocalHosts.stream()
                                         .filter(h -> !selectedHosts.contains(h) && h.isUp())
                                         .collect(Collectors.toList());

            if (nonLocalHosts.size() < requiredNonLocalHosts)
            {
                LOGGER.warn("Could not find enough new, up non-local hosts to meet requested number {}",
                            requiredNonLocalHosts);
            }
            else
            {
                LOGGER.debug("Found enough new, up, non-local hosts to meet requested number {}",
                             requiredNonLocalHosts);
            }
            if (nonLocalHosts.size() > requiredNonLocalHosts)
            {
                Collections.shuffle(nonLocalHosts, this.random);
            }
            int hostsToAdd = Math.min(requiredNonLocalHosts, nonLocalHosts.size());
            for (int i = 0; i < hostsToAdd; i++)
            {
                selectedHosts.add(nonLocalHosts.get(i));
            }
        }
    }