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.
500097
private Connection getConnection(InetSocketAddress addr,
                                   Class<?> protocol,
                                   UserGroupInformation ticket,
                                   int rpcTimeout,
                                   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, ticket, rpcTimeout);
    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.
    boolean success = false;
    try {
      connection.setupIOstreams();
      success = true;
    } finally {
      if (!success) {
        // We need to make sure connection is removed from connections object if
        // there is any unhandled exception (like OOM). In this case, unlikely
        // there is response thread started which can clear the connection
        // eventually.
        try {
          if (connection.closeException == null) {
            connection.markClosed(new IOException(
                "Unexpected error when setup IO Stream"));
          }
        } finally {
          connection.close(true);
        }
      }
    }
    return connection;
  }
309463
@Override
    public Connection makeObject(ObjectPoolWithThreadAffinity<Connection> pool) throws Exception
    {
        Connection conn = connectionFactory.createConnection();
        return new PooledConnection(conn, pool, this.statementsToPool);
    }
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
905675
ConnectionWrapper obtainConnection() {
		synchronized (allConnections) {
			//fails if connection pool not started
			if (!availableConnections.isEmpty()) {
				//retrieve and remove first connection from list
				//  since released connections are added to the back, connections will rotate
				ConnectionWrapper connWrap = (ConnectionWrapper) availableConnections.remove(0);
				usedConnections.add(connWrap);
				if (usedConnections.size() > maxNrOfConcurrentConnectionsCounted) {
					maxNrOfConcurrentConnectionsCounted = usedConnections.size();
				}
				return connWrap;
			} else {
				//create one if max not reached
				//this also restores lost connections
				if ((allConnections.size() < initialNrofConnections) || (allConnections.size() < maxNrofConnections)) {
					try {
						ConnectionWrapper connWrap = createConnectionWrapper(dbUrl, dbUsername, dbUserpassword);

						allConnections.add(connWrap);
						usedConnections.add(connWrap);

						System.out.println(new LogEntry("Creating new Connection, now " + allConnections.size() + " in use"));

						return connWrap;
					} catch (SQLException sqle) {
						//happens if db unreachable
						//connection will be lost for the time being
						nrofErrors++;
						System.out.println(new LogEntry("Cannot create new connection to " + dbUrl + " unreachable or useless connection settings", sqle));
						throw new ResourceException("Cannot create new connection to " + dbUrl + " unreachable or useless connection settings", sqle);
					}
				} else {
					System.out.println(new LogEntry("maximum nr of connections (" + maxNrofConnections + ") reached while Application demands another"));
				}
				return null;
			}
		}
	}
460640
async def _connect(self, hostname, port, reconnect=False, channels=[],
                       encoding=protocol.DEFAULT_ENCODING, source_address=None):
        
        # Create connection if we can't reuse it.
        if not reconnect or not self.connection:
            self._autojoin_channels = channels
            self.connection = connection.Connection(hostname, port, source_address=source_address,
                                                    eventloop=self.eventloop)
            self.encoding = encoding

        # Connect.
        await self.connection.connect()
995307
def _acquire_connection(self, host, port, use_ssl=False, tunnel=True):
        ''''''
        if hasattr(self._connection_pool, 'acquire_proxy'):
            connection = yield from \
                self._connection_pool.acquire_proxy(host, port, use_ssl,
                                                    tunnel=tunnel)
        else:
            connection = yield from \
                self._connection_pool.acquire(host, port, use_ssl)

        self._connections.add(connection)

        return connection
194700
def get_connection(self, host, port):
        
        return beanstalkc.Connection(
            host=host,
            port=port
        )
256571
def _get_conn(self, host, port):
        """"""
        host_key = (host, port)
        if host_key not in self.conns:
            self.conns[host_key] = KafkaConnection(
                host,
                port,
                timeout=self.timeout
            )

        return self.conns[host_key]
200506
def _get_new_connection(self, conn_params):
    """"""
    self.__connection_string = conn_params.get('connection_string', '')
    conn = self.Database.connect(**conn_params)
    return conn
663979
def get_http_connection(self, host, is_secure):
        
        self.clean()
        with self.mutex:
            key = (host, is_secure)
            if key not in self.host_to_pool:
                return None
            return self.host_to_pool[key].get()
673025
@Override
    public final synchronized boolean addHost(Host host, boolean refresh) {
        // Already exists
        if (hosts.containsKey(host)) {
            // Check to see if we are adding token ranges or if the token ranges changed
            // which will force a rebuild of the token topology
            Host existingHost = hosts.get(host).getHost();
            if (existingHost.getTokenRanges().size() != host.getTokenRanges().size()) {
                existingHost.setTokenRanges(host.getTokenRanges());
                return true;
            }
            
            ArrayList<TokenRange> currentTokens = Lists.newArrayList(existingHost.getTokenRanges());
            ArrayList<TokenRange> newTokens     = Lists.newArrayList(host.getTokenRanges());
            Collections.sort(currentTokens, compareByStartToken);
            Collections.sort(newTokens,     compareByStartToken);
            for (int i = 0; i < currentTokens.size(); i++) {
                if (!currentTokens.get(i).getStartToken().equals(newTokens.get(i).getStartToken()) ||
                    !currentTokens.get(i).getEndToken().equals(newTokens.get(i).getEndToken())) {
                    return false;
                }
            }
            
            existingHost.setTokenRanges(host.getTokenRanges());
            return true;
        }
        else {
            HostConnectionPool<CL> pool = newHostConnectionPool(host, factory, config);
            if (null == hosts.putIfAbsent(host, pool)) {
                try {
                    monitor.onHostAdded(host, pool);
                    if (refresh) {
                        topology.addPool(pool);
                        rebuildPartitions();
                    }
                    pool.primeConnections(config.getInitConnsPerHost());
                }
                catch (Exception e) {
                    // Ignore, pool will have been marked down internally
                }
                return true;
            }
            else {
                return false;
            }
        }
    }
629143
private void initPool() {
        if (logger.isWarnEnabled()) {
            logger.warn("Start to initialize connection pool with url: " + url + " ...");
        }

        for (int i = 0; (i < initialSize) && (xpool.size() < initialSize); i++) {
            pool.lock();

            try {
                if (pool.isClosed()) {
                    break;
                }

                if ((i < initialSize) && (xpool.size() < initialSize)) {
                    PoolableConnection poolableConn = newConnection();

                    if (!pool.add(poolableConn)) {
                        detroyConnection(poolableConn);
                    }
                }
            } finally {
                pool.unlock();
            }
        }

        if (logger.isWarnEnabled()) {
            logger.warn("End to initialize connection pool with url: " + url + " ...");
        }
    }
562857
public static Connection newInstance(Connection conn) {
        return (Connection) java.lang.reflect.Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[]{Connection.class},
                new ConnectionProxy(conn));
        /*
        return (Connection) java.lang.reflect.Proxy.newProxyInstance(conn.getClass().getClassLoader(), conn.getClass().getInterfaces(),
                new ConnectionProxy(conn));
                */
    }
491828
def add_pool_member(self, name, port, pool_name):
        '''
        
        '''
        if not self.check_pool(pool_name):
            raise CommandExecutionError(
                '{0} pool does not exists'.format(pool_name)
            )

        members_seq = self.bigIP.LocalLB.Pool.typefactory.create(
            'Common.IPPortDefinitionSequence'
        )
        members_seq.items = []

        member = self.bigIP.LocalLB.Pool.typefactory.create(
            'Common.IPPortDefinition'
        )

        member.address = name
        member.port = port

        members_seq.items.append(member)

        try:
            self.bigIP.LocalLB.Pool.add_member(pool_names=[pool_name],
                                               members=[members_seq])
        except Exception as e:
            raise Exception(
                'Unable to add `{0}` to `{1}`\n\n{2}'.format(name,
                                                             pool_name,
                                                             e)
            )
        return True
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
651105
def create_connector_c_pool(name, server=None, **kwargs):
    '''
    
    '''
    defaults = {
        'connectionDefinitionName': 'javax.jms.ConnectionFactory',
        'resourceAdapterName': 'jmsra',
        'associateWithThread': False,
        'connectionCreationRetryAttempts': 0,
        'connectionCreationRetryIntervalInSeconds': 0,
        'connectionLeakReclaim': False,
        'connectionLeakTimeoutInSeconds': 0,
        'description': '',
        'failAllConnections': False,
        'id': name,
        'idleTimeoutInSeconds': 300,
        'isConnectionValidationRequired': False,
        'lazyConnectionAssociation': False,
        'lazyConnectionEnlistment': False,
        'matchConnections': True,
        'maxConnectionUsageCount': 0,
        'maxPoolSize': 32,
        'maxWaitTimeInMillis': 60000,
        'ping': False,
        'poolResizeQuantity': 2,
        'pooling': True,
        'steadyPoolSize': 8,
        'target': 'server',
        'transactionSupport': '',
        'validateAtmostOncePeriodInSeconds': 0
    }

    # Data = defaults + merge kwargs + remove salt
    data = defaults
    data.update(kwargs)

    # Check TransactionSupport against acceptable values
    if data['transactionSupport'] and data['transactionSupport'] not in (
               'XATransaction',
               'LocalTransaction',
               'NoTransaction'
       ):
        raise CommandExecutionError('Invalid transaction support')

    return _create_element(name, 'resources/connector-connection-pool', data, server)
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
          }
        }
      });
    }
  }