Get a connection from the pool, or create a new one and add it to the
pool. Connections to a given host/port are reused.
772613
private Connection getConnection(InetSocketAddress addr, Class<?> protocol, Call call) throws IOException {
		if (!running.get()) {
			// the client is stopped
			throw new IOException("The client is stopped");
		}
		Connection connection;
		/*
		 * we could avoid this allocation for each RPC by having a
		 * connectionsId object and with set() method. We need to manage the
		 * refs for keys in HashMap properly. For now its ok.
		 */
		ConnectionId remoteId = new ConnectionId(addr, protocol);
		do {
			synchronized (connections) {
				connection = connections.get(remoteId);
				if (connection == null) {
					connection = new Connection(remoteId);
					connections.put(remoteId, connection);
				}
			}
		} while (!connection.addCall(call));

		// we don't invoke the method below inside "synchronized (connections)"
		// block above. The reason for that is if the server happens to be slow,
		// it will take longer to establish a connection and that will slow the
		// entire system down.
		connection.setupIOstreams();
		return connection;
	}
715034
private void addConnectionRequest() {
    if (totalConnection.get() < options.maxPoolSize && poolState.get() == POOL_STATE_OK) {

      //ensure to have one worker if was timeout
      connectionAppender.prestartCoreThread();
      connectionAppenderQueue.offer(() -> {

        if ((totalConnection.get() < options.minPoolSize || pendingRequestNumber.get() > 0)
            && totalConnection.get() < options.maxPoolSize) {
          try {
            addConnection();
          } catch (SQLException sqle) {
            //eat
          }
        }
      });
    }
  }
652885
private PooledConnection createPooledConnection(JDBCConnection connection)
    throws SQLException {

        LifeTimeConnectionWrapper connectionWrapper =
            new LifeTimeConnectionWrapper(connection, this.connectionDefaults);
        JDBCPooledConnection pooledConnection =
            new JDBCPooledConnection(connectionWrapper);

        connectionWrapper.setPooledConnection(pooledConnection);

        return pooledConnection;
    }
832900
def connection(state = nil, &block)
      opts = merge_options(options, state || {})
      validate_options(opts)
      conn_opts = connection_options(opts)

      if @connection && @connection_options == conn_opts
        reuse_connection(&block)
      else
        create_new_connection(conn_opts, &block)
      end
    end
775521
def add_connection(self, host):
        
        self.hosts.append(host)
        self.set_connections(self.hosts)
598537
private MBeanServerConnection createServerConnection(String host, int port) throws IOException {
            jmxServiceURL = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
            JMXConnector jmxc = JMXConnectorFactory.connect(jmxServiceURL, null);
            return jmxc.getMBeanServerConnection();            
    }
498619
async def create_connection(self, address=None, protocol_factory=None,
                                **kwargs):
        
        loop = self._loop
        protocol_factory = protocol_factory or self.create_protocol
        if isinstance(address, tuple):
            kwargs['host'] = address[0]
            kwargs['port'] = address[1]
        _, protocol = await loop.create_connection(protocol_factory, **kwargs)
        event = protocol.event('connection_made')
        if not event.fired():
            await event.waiter()
        return protocol
1183294
def acquire_direct(self, address):
        
        if self.closed():
            raise ServiceUnavailable("Connection pool closed")
        with self.lock:
            try:
                connections = self.connections[address]
            except KeyError:
                connections = self.connections[address] = deque()

            connection_acquisition_start_timestamp = perf_counter()
            while True:
                # try to find a free connection in pool
                for connection in list(connections):
                    if connection.closed() or connection.defunct() or connection.timedout():
                        connections.remove(connection)
                        continue
                    if not connection.in_use:
                        connection.in_use = True
                        return connection
                # all connections in pool are in-use
                infinite_connection_pool = (self._max_connection_pool_size < 0 or
                                            self._max_connection_pool_size == float("inf"))
                can_create_new_connection = infinite_connection_pool or len(connections) < self._max_connection_pool_size
                if can_create_new_connection:
                    try:
                        connection = self.connector(address)
                    except ServiceUnavailable:
                        self.remove(address)
                        raise
                    else:
                        connection.pool = self
                        connection.in_use = True
                        connections.append(connection)
                        return connection

                # failed to obtain a connection from pool because the pool is full and no free connection in the pool
                span_timeout = self._connection_acquisition_timeout - (perf_counter() - connection_acquisition_start_timestamp)
                if span_timeout > 0:
                    self.cond.wait(span_timeout)
                    # if timed out, then we throw error. This time computation is needed, as with python 2.7, we cannot
                    # tell if the condition is notified or timed out when we come to this line
                    if self._connection_acquisition_timeout <= (perf_counter() - connection_acquisition_start_timestamp):
                        raise ClientError("Failed to obtain a connection from pool within {!r}s".format(
                            self._connection_acquisition_timeout))
                else:
                    raise ClientError("Failed to obtain a connection from pool within {!r}s".format(self._connection_acquisition_timeout))
1090396
def make_connection(self):
        ""
        if self._created_connections >= self.max_connections:
            raise ConnectionError("Too many connections")
        self._created_connections += 1
        return self.connection_class(**self.connection_kwargs)
965609
public int getConnectionPoolSize(String host, int port) {
        RequestBuilder req = new RequestBuilder();
        req.host = host;
        req.port = port;
        return _getPoolSize(req);
    }
905916
def add_or_renew_pool(self, host, is_host_addition):
        
        distance = self._profile_manager.distance(host)
        if distance == HostDistance.IGNORED:
            return None

        def run_add_or_renew_pool():
            try:
                if self._protocol_version >= 3:
                    new_pool = HostConnection(host, distance, self)
                else:
                    # TODO remove host pool again ???
                    new_pool = HostConnectionPool(host, distance, self)
            except AuthenticationFailed as auth_exc:
                conn_exc = ConnectionException(str(auth_exc), host=host)
                self.cluster.signal_connection_failure(host, conn_exc, is_host_addition)
                return False
            except Exception as conn_exc:
                log.warning("Failed to create connection pool for new host %s:",
                            host, exc_info=conn_exc)
                # the host itself will still be marked down, so we need to pass
                # a special flag to make sure the reconnector is created
                self.cluster.signal_connection_failure(
                    host, conn_exc, is_host_addition, expect_host_to_be_down=True)
                return False

            previous = self._pools.get(host)
            with self._lock:
                while new_pool._keyspace != self.keyspace:
                    self._lock.release()
                    set_keyspace_event = Event()
                    errors_returned = []

                    def callback(pool, errors):
                        errors_returned.extend(errors)
                        set_keyspace_event.set()

                    new_pool._set_keyspace_for_all_conns(self.keyspace, callback)
                    set_keyspace_event.wait(self.cluster.connect_timeout)
                    if not set_keyspace_event.is_set() or errors_returned:
                        log.warning("Failed setting keyspace for pool after keyspace changed during connect: %s", errors_returned)
                        self.cluster.on_down(host, is_host_addition)
                        new_pool.shutdown()
                        self._lock.acquire()
                        return False
                    self._lock.acquire()
                self._pools[host] = new_pool

            log.debug("Added pool for host %s to session", host)
            if previous:
                previous.shutdown()

            return True

        return self.submit(run_add_or_renew_pool)
549847
function getConnection(options) {
  debug('getConnection','start',options);

  let key = null;
  let promise = null;
  try {
    //clone options
    options = clone(options);

    //serialize the options as a key for pools
    key = stringify(options || {});

    //if there's already a promise for the given connection, return it
    if (promises[key]) return promises[key];

    //create a new promise for the given connection options
    promise = promises[key] = createConnectionPromise(key, options);

    debug('getConnection','success')
    return promise;
  } catch(err) {
    debug('getConnection','error',err);
    return Promise.reject(err);
  }
}
786984
def get_connection_by_node(self, node):
        
        self._checkpid()
        self.nodes.set_node_name(node)

        try:
            # Try to get connection from existing pool
            connection = self._available_connections.get(node["name"], []).pop()
        except IndexError:
            connection = self.make_connection(node)

        self._in_use_connections.setdefault(node["name"], set()).add(connection)

        return connection
651596
function Connection(conn) {
	if(!(this instanceof Connection)) {
		return new Connection(conn);
	}
	var self = this;
	if(!conn) { throw new TypeError("no connection set"); }
	self._connection = conn;
	self._connect    = Q.nfbind(self._connection.connect.bind(self._connection));
	self._query      = Q.nfbind(self._connection.query.bind(self._connection));

	// These do not have callbacks when PoolConnection is used
	//self._end        = Q.nfbind(self._connection.end.bind(self._connection));
	//self._release        = Q.nfbind(self._connection.release.bind(self._connection));

	self._changeUser = Q.nfbind(self._connection.changeUser.bind(self._connection));
	db.Connection.call(self, conn);
}
611310
def _connection(self):
    '''
    
    '''
    try:
      return self._pool.get(False)
    except Empty:
      args = [
        self._host, self._port, self._keyspace
      ]
      kwargs = {
        'user'              : None,
        'password'          : None,
        'cql_version'       : self._cql_version,
        'compression'       : self._compression,
        'consistency_level' : self._consistency_level,
        'transport'         : self._transport,
      }
      if self._credentials:
        kwargs['user'] = self._credentials['user']
        kwargs['password'] = self._credentials['password']
      return cql.connect(*args, **kwargs)
673557
def make_connection(self):
        ""
        connection = self.connection_class(**self.connection_kwargs)
        self._connections.append(connection)
        return connection
143245
def _connect(self):
        
        # Attempt to get a cached connection from the connection pool
        try:
            connection = self._pool_manager.get(self.pid, self)
            LOGGER.debug("Re-using connection for %s", self.pid)
        except pool.NoIdleConnectionsError:
            if self._pool_manager.is_full(self.pid):
                raise

            # Create a new PostgreSQL connection
            kwargs = utils.uri_to_kwargs(self._uri)
            LOGGER.debug("Creating a new connection for %s", self.pid)
            connection = self._psycopg2_connect(kwargs)

            self._pool_manager.add(self.pid, connection)
            self._pool_manager.lock(self.pid, connection, self)

            # Added in because psycopg2ct connects and leaves the connection in
            # a weird state: consts.STATUS_DATESTYLE, returning from
            # Connection._setup without setting the state as const.STATUS_OK
            if utils.PYPY:
                connection.reset()

            # Register the custom data types
            self._register_unicode(connection)
            self._register_uuid(connection)

        return connection