This method is overridden to provide a more efficient implementation which does not iterate through
all servers. This is under the assumption that in most cases, there are more available instances
than not.
502850
@Override
    public Server choose(Object key) {
        int count = 0;
        Server server = roundRobinRule.choose(key);
        while (count++ <= 10) {
            if (server != null && predicate.apply(new PredicateKey(server))) {
                return server;
            }
            server = roundRobinRule.choose(key);
        }
        return super.choose(key);
    }
1285067
@Override
    public List<Server> getEligibleServers(List<Server> servers, Object loadBalancerKey) {
        List<Server> result = super.getEligibleServers(servers, loadBalancerKey);
        Iterator<AbstractServerPredicate> i = fallbacks.iterator();
        while (!(result.size() >= minimalFilteredServers && result.size() > (int) (servers.size() * minimalFilteredPercentage))
                && i.hasNext()) {
            AbstractServerPredicate predicate = i.next();
            result = predicate.getEligibleServers(servers, loadBalancerKey);
        }
        return result;
    }
1310605
@Override
	public ThriftServer getThriftServer(String serverName, int serverPort, Map<String, Service> serviceMap) {
		return getThriftServer(serverName, serverPort, buildMultiplexedProcessor(serviceMap));
	}
802001
private void addLoadBalancerListener() {
        if (!(lbContext.getLoadBalancer() instanceof BaseLoadBalancer)) {
            return;
        }
        
        ((BaseLoadBalancer) lbContext.getLoadBalancer()).addServerListChangeListener(new ServerListChangeListener() {
            @Override
            public void serverListChanged(List<Server> oldList, List<Server> newList) {
                Set<Server> removedServers = new HashSet<Server>(oldList);
                removedServers.removeAll(newList);
                for (Server server: rxClientCache.keySet()) {
                    if (removedServers.contains(server)) {
                        // this server is no longer in UP status
                        removeClient(server);
                    }
                }
            }
        });
    }
1305454
@Override
	public ThriftServer getNonblockingThriftServer(String serverName, int serverPort, TProcessor processor) {
		return new NonblockingThriftServerImpl(serverName, serverPort, thriftServerConfiguration, processor);
	}
1339095
@Override
	public InstanceExample nextInstance() {
		InstanceExample prevInstance = this.lastInstanceRead;
		if (prevInstance != null) {
			this.numInstancesRead++;
		}
		try {
			String line;
			do {
				line = this.fileReader.readLine();
				if (line == null) {
					break;
				}
				line = line.trim();
			} while (line.isEmpty() || line.charAt(0) == '%'
					|| line.charAt(0) == '@');

			if (line != null) {
				StringTokenizer token = new StringTokenizer(line,
						splitCharOption.getValue());

				double[] value = new double[this.numAttributes];
				int i;
				for (i = 0; i < this.numTokens && token.hasMoreTokens(); i++) {
					value[i] = Double.valueOf(token.nextToken());
				}
				if (i < this.numTokens || token.hasMoreTokens()) {
					throw new RuntimeException(
							"Next Instance has an wrong cardinality!");
				}
				this.lastInstanceRead = new InstanceExample(new DenseInstance(1, value));
				this.lastInstanceRead.getData().setDataset(this.dataset);
				this.hitEndOfFile = false;
			} else {
				this.lastInstanceRead = null;
				this.hitEndOfFile = true;
			}
		} catch (IOException ioe) {
			throw new RuntimeException("Read next Instance failed.", ioe);
		}
		return prevInstance;
	}
375983
private void ensureAvailable(int index) {
        if (data.get(index) != null) {
            // Already have this item.
            return;
        }
        if (client == null) {
            throw new RuntimeException("no remoting client configured");
        }
        Object result;
        int start = index;
        int count;
        if (mode.equals(MODE_ONDEMAND)) {
            // Only get requested item
            count = 1;
        } else if (mode.equals(MODE_FETCHALL)) {
            // Get remaining items
            count = totalCount - cursor;
        } else if (mode.equals(MODE_PAGE)) {
            // Get next page
            // TODO: implement prefetching of multiple pages
            count = 1;
            for (int i = 1; i < pageSize; i++) {
                if (this.data.get(start + i) == null) {
                    count += 1;
                }
            }
        } else {
            // Default to "ondemand"
            count = 1;
        }

        result = client.invokeMethod(serviceName + ".getRecords", new Object[] { id, start + 1, count });
        if (!(result instanceof RecordSetPage)) {
            throw new RuntimeException("expected RecordSetPage but got " + result);
        }

        RecordSetPage page = (RecordSetPage) result;
        if (page.getCursor() != start + 1) {
            throw new RuntimeException("expected offset " + (start + 1) + " but got " + page.getCursor());
        }

        List<List<Object>> data = page.getData();
        if (data.size() != count) {
            throw new RuntimeException("expected " + count + " results but got " + data.size());
        }

        // Store received items
        for (int i = 0; i < count; i++) {
            this.data.add(start + i, data.get(i));
        }
    }
743783
private Object instanceNotYetLoaded(
		final Tuple resultset,
		final int i,
		final Loadable persister,
		final String rowIdAlias,
		final org.hibernate.engine.spi.EntityKey key,
		final LockMode lockMode,
		final org.hibernate.engine.spi.EntityKey optionalObjectKey,
		final Object optionalObject,
		final List hydratedObjects,
		final SharedSessionContractImplementor session)
	throws HibernateException {
		final String instanceClass = getInstanceClass(
				resultset,
				i,
				persister,
				key.getIdentifier(),
				session
			);

		final Object object;
		if ( optionalObjectKey != null && key.equals( optionalObjectKey ) ) {
			//its the given optional object
			object = optionalObject;
		}
		else {
			// instantiate a new instance
			object = session.instantiate( instanceClass, key.getIdentifier() );
		}

		//need to hydrate it.

		// grab its state from the ResultSet and keep it in the Session
		// (but don't yet initialize the object itself)
		// note that we acquire LockMode.READ even if it was not requested
		LockMode acquiredLockMode = lockMode == LockMode.NONE ? LockMode.READ : lockMode;
		loadFromResultSet(
				resultset,
				i,
				object,
				instanceClass,
				key,
				rowIdAlias,
				acquiredLockMode,
				persister,
				session
			);

		//materialize associations (and initialize the object) later
		hydratedObjects.add( object );

		return object;
	}
492374
@SuppressWarnings("NullableProblems")
  @Override
  public Iterator<T> iterator() {
    return new Iterator<T>() {
      private int index = 0;

      @Override
      public boolean hasNext() {
        return this.index < size();
      }

      @Override
      public T next() {
        if (this.index >= size()) {
          throw new NoSuchElementException(this.index + ">=" + size());
        }
        return getElementAt(this.index++);
      }

      @Override
      public void remove() {
        throw new UnsupportedOperationException("Removing is unsupported here");
      }

    };
  }
182347
public static void putOverloadMethodCache(String serviceName, Method method) {
        ConcurrentHashMap<String, Method> cache = OVERLOAD_METHOD_CACHE.get(serviceName);
        if (cache == null) {
            cache = new ConcurrentHashMap<String, Method>();
            ConcurrentHashMap<String, Method> old = OVERLOAD_METHOD_CACHE.putIfAbsent(serviceName, cache);
            if (old != null) {
                cache = old;
            }
        }
        StringBuilder mSigs = new StringBuilder(128);
        mSigs.append(method.getName());
        for (Class<?> paramType : method.getParameterTypes()) {
            mSigs.append(paramType.getName());
        }
        cache.putIfAbsent(mSigs.toString(), method);
    }
254925
protected void compareServerMode(Session other) throws ClientException {

        if (serverMode == SERVER_DEFAULT &&
            other.serverMode == SERVER_DEFAULT) {
            // this is OK
        } else {
            // active and passive side had already been set;
            // make sure that it has been done correctly:
            // either server can be active
            // providing that the other is passive

            // if this server mode has been defined,
            // but the other has not, we can't proceed
            if (this.serverMode == SERVER_DEFAULT ||
                other.serverMode == SERVER_DEFAULT) {
                throw new ClientException(ClientException.BAD_SERVER_MODE,
                        "Only one server has been defined as active or passive");
            }

            // both servers cannot have the same mode
            if (other.serverMode == this.serverMode) {
                String modeStr = (this.serverMode == SERVER_PASSIVE) ? "passive"
                        : "active";
                throw new ClientException(ClientException.BAD_SERVER_MODE,
                        "Both servers are " + modeStr);
            }
        }
    }
153410
private void deployInstances(List<InstanceContext> instances, final Handler<AsyncResult<Void>> doneHandler) {
    final CountingCompletionHandler<Void> counter = new CountingCompletionHandler<Void>(instances.size()).setHandler(doneHandler);
    for (final InstanceContext instance : instances) {
      // Before deploying the instance, check if the instance is already deployed in
      // the network's cluster.
      deploymentIDs.get(instance.address(), new Handler<AsyncResult<String>>() {
        @Override
        public void handle(AsyncResult<String> result) {
          if (result.failed()) {
            counter.fail(result.cause());
          } else if (result.result() == null) {
            // If no deployment ID has been assigned to the instance then that means it hasn't
            // yet been deployed. Deploy the instance.
            deployInstance(instance, counter);
          } else {
            // Even if the instance is already deployed, update its context in the cluster.
            // It's possible that the instance's connections could have changed with the update.
            data.put(instance.address(), Contexts.serialize(instance).encode(), new Handler<AsyncResult<String>>() {
              @Override
              public void handle(AsyncResult<String> result) {
                if (result.failed()) {
                  counter.fail(result.cause());
                } else {
                  counter.succeed();
                }
              }
            });
          }
        }
      });
    }
  }
34666
public final void server() {

    // load parameters into a properties
    String port = parsedArguments.getString("port");
    String model = parsedArguments.getString("model");
    String headFinder = parsedArguments.getString("headFinder");
    String outputFormat = parsedArguments.getString("outputFormat");
    // language parameter
    String lang = parsedArguments.getString("language");
    Properties serverproperties = setServerProperties(port, model, lang, headFinder, outputFormat);
    new ConstituentParserServer(serverproperties);
  }
788914
@Override
	public Iterator<E> iterator() {
		return new Iterator<E>() {
			private PQueue<E> queue = AmortizedPQueue.this;
			public boolean hasNext() {
				return queue.size() > 0;
			}

			public E next() {
				E e = queue.peek();
				queue = queue.minus();
				return e;
			}

			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}
154083
public java.util.List<InstanceCapacity> getAvailableInstanceCapacity() {
        if (availableInstanceCapacity == null) {
            availableInstanceCapacity = new com.amazonaws.internal.SdkInternalList<InstanceCapacity>();
        }
        return availableInstanceCapacity;
    }
1041672
def ensure_server(data)
      if @servers.include?(data['id'].to_i)
        @servers[data['id'].to_i]
      else
        @servers[data['id'].to_i] = Server.new(data, self)
      end
    end
330684
protected synchronized void refreshServers() {
        StringBuilder refreshResult = new StringBuilder();
        Set<Server> availableReadServers = new HashSet<>();
        Server[] newReadServers;

        if (writeServer == null || !writeServer.isAvailable()) {
            logger.debug("[refreshServers] write server is null or not available");

            for (Server server : SERVERS) {
                if (server.isAvailable() && server.isMaster()) {
                    writeServer = server;
                    logger.debug("[refreshServers] new writeServer: id = {}, uri = {}", writeServer.getId(), writeServer.getManagementUri());
                }
            }

            if (writeServer == null) {
                readServers = new Server[0];
                return;
            }
        }

        for (Server server : SERVERS) {
            logger.debug("[refreshServers] server: id = {}, isAvailable = {}", server.getId(), server.isAvailable());

            if (!server.getId().equals(writeServer.getId()) && server.isAvailable()) {
                logger.debug("[refreshServers] add read server");
                availableReadServers.add(server);
            }
        }

        if (availableReadServers.size() == 0) {
            logger.debug("[refreshServers] available read servers = 0");

            newReadServers = new Server[1];
            newReadServers[0] = writeServer;

            refreshResult
                    .append("refreshServers: read servers = ")
                    .append(writeServer.getId())
                    .append("=>")
                    .append(writeServer.getManagementUri())
                    .append(", write servers = ")
                    .append(writeServer.getId())
                    .append("=>")
                    .append(writeServer.getManagementUri());
        }
        else {
            logger.debug("[refreshServers] available read servers = {}", availableReadServers.size());

            newReadServers = new Server[availableReadServers.size()];
            int i = 0;

            refreshResult.append("refreshServers: read servers = [");

            for (Server server : availableReadServers) {
                newReadServers[i++] = server;

                refreshResult
                        .append(server.getId())
                        .append("=>")
                        .append(server.getManagementUri())
                        .append(" ");
            }

            refreshResult
                    .append(", write servers = ")
                    .append(writeServer.getId())
                    .append("=>")
                    .append(writeServer.getManagementUri())
                    .append("]");
        }

        readServers = newReadServers;

        logger.debug("[refreshServers] {}", refreshResult.toString());
    }