Get from pool, or create one without locking, if needed.
973861
private DocumentBuilder getDocumentBuilderFromPool()
            throws ParserConfigurationException {
        DocumentBuilder builder = documentBuilderPool.pollFirst();
        if (builder == null){
            builder = getDomFactory().newDocumentBuilder();
        }
        builder.setErrorHandler(errorHandler);
        return builder;
    }
310960
private synchronized PoolableConnection newConnection() {
        synchronized (xpool) {
            if (xpool.size() >= maxActive) {
                return null;
            }

            try {
                PoolableConnection conn = null;

                if (xpool.size() < minIdle) {
                    conn = new PoolableConnection(this, ds.getConnection(), liveTime, Integer.MAX_VALUE, maxOpenPreparedStatementsPerConnection);
                } else if (xpool.size() < maxIdle) {
                    conn = new PoolableConnection(this, ds.getConnection(), liveTime, maxIdleTime, maxOpenPreparedStatementsPerConnection);
                } else {
                    conn = new PoolableConnection(this, ds.getConnection(), liveTime, 60 * 1000L, maxOpenPreparedStatementsPerConnection);
                }

                xpool.put(conn, conn);

                if (logger.isWarnEnabled()) {
                    logger.warn("The " + xpool.size() + "th of " + maxActive + " connections is created for data source: " + url);
                }

                return conn;
            } catch (SQLException e) {
                String msg = "Faied to create new connection for data source '" + url + "'." + " [Active connection number]: " + (xpool.size() + 1) + ". "
                        + AbacusException.getErrorMsg(e);
                logger.error(msg, e);
                throw new UncheckedSQLException(msg, e);
            }
        }
    }
1155588
def require_p p_kls
            l = @pool[p_kls]
            return p_kls.new if l.nil?
            p = l.pop
            return p_kls.new if p.nil?
            p
        end
629969
async def acquire(self, command=None, args=()):
        
        if self.closed:
            raise PoolClosedError("Pool is closed")
        async with self._cond:
            if self.closed:
                raise PoolClosedError("Pool is closed")
            while True:
                await self._fill_free(override_min=True)
                if self.freesize:
                    conn = self._pool.popleft()
                    assert not conn.closed, conn
                    assert conn not in self._used, (conn, self._used)
                    self._used.add(conn)
                    return conn
                else:
                    await self._cond.wait()
1142498
def free(cls, pid, connection):
        
        with cls._lock:
            LOGGER.debug('Freeing %s from pool %s', id(connection), pid)
            cls._ensure_pool_exists(pid)
            cls._pools[pid].free(connection)
498659
def _pool_get(get, results, next_available, task_next_lock, to_skip, \
                  task_num, pool_size, id_self):
        
        log.debug('NuMap(%s) started pool_getter' % id_self)
        # should return when all workers have returned, each worker sends a 
        # sentinel before returning. Before returning it should send sentinels to
        # all tasks but the next available queue should be released only if we 
        # know that no new results will arrive.
        sentinels = 0
        result_ids, last_result_id, very_last_result_id = {}, {}, {}
        for i in xrange(task_num):
            last_result_id[i] = -1
            very_last_result_id[i] = -2
            result_ids[i] = set()

        while True:
            try:
                log.debug('NuMap(%s) pool_getter waits for a result.' % id_self)
                #gc.disable()
                result = get()
                #gc.enable()
            except (IOError, EOFError):
                log.error('NuMap(%s) pool_getter has a pipe problem.' % id_self)
                break

            # got a sentinel?
            if result is None:
                sentinels += 1
                log.debug('NuMap(%s) pool_getter got a sentinel.' % id_self)
                if sentinels == pool_size:
                    log.debug('NuMap(%s) pool_getter got all sentinels.' % \
                              id_self)
                    # here we are escaping.
                    break
                else:
                    # waiting for more sentinels or results to come.
                    continue

            # got a sentinel for a task?
            # only one sentinel per task will be received
            if result[1] is None:
                task = result[0]
                very_last_result_id[task] = result[2]
                if last_result_id[task] == very_last_result_id[task]:
                    results[task].put(('stop', False, 'stop'))
                    next_available[task].put(True)
                    log.debug('NuMap(%s) pool_getter sent sentinel for task %s.'\
                                                            % (id_self, task))
                continue

            # got some result for some task, which might be an exception
            task, i, is_valid, real_result = result
            # locked if next for this task is in 
            # the process of raising a TimeoutError
            task_next_lock[task].acquire()
            log.debug('NuMap(%s) pool_getter received result %s for task %s)' % \
                      (id_self, i, task))

            if to_skip[task]:
                log.debug('NuMap(%s) pool_getter skips results: %s' % (id_self, \
                range(last_result_id[task] + 1, last_result_id[task] + \
                      to_skip[task] + 1)))
                last_result_id[task] += to_skip[task]
                to_skip[task] = 0

            if i > last_result_id[task]:
                result_ids[task].add(i)
                results[task].put((i, is_valid, real_result))
                log.debug('NuMap(%s) pool_getter put result %s for task %s to queue' % \
                          (id_self, i, task))
            else:
                log.debug('NuMap(%s) pool_getter skips result %s for task %s' % \
                          (id_self, i, task))

            # this releases the next method for each ordered result in the queue
            # if the NuMap instance is ordered =False this information is 
            # ommitted.
            while last_result_id[task] + 1 in result_ids[task]:
                next_available[task].put(True)
                last_result_id[task] += 1
                log.debug('NuMap(%s) pool_getter released task: %s' % \
                          (id_self, task))
            if last_result_id[task] == very_last_result_id[task]:
                results[task].put(('stop', False, 'stop'))
                next_available[task].put(True)
            # release the next method
            task_next_lock[task].release()
        log.debug('NuMap(%s) pool_getter returns' % id_self)
294132
def get(self, timeout=None):
        """"""
        if timeout:
            try:
                result = self._queue.get(True, timeout)
            except multiprocessing.Queue.Empty:
                return(False, None)
            return(True, result)
        return self._queue.get()
959433
def _get_template_pool_lock(self, id):
        """"""
        try:
            return self._hosting_device_locks[id]
        except KeyError:
            self._hosting_device_locks[id] = threading.Lock()
            return self._hosting_device_locks.get(id)
713602
function pool(promiseFactories, limit) {
  return new Promise(function (resolve, reject) {
    var running = 0;
    var current = 0;
    var done = 0;
    var len = promiseFactories.length;
    var err;

    function runNext() {
      running++;
      promiseFactories[current++]().then(onSuccess, onError);
    }

    function doNext() {
      if (++done === len) {
        /* istanbul ignore if */
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      } else {
        runNextBatch();
      }
    }

    function onSuccess() {
      running--;
      doNext();
    }

    /* istanbul ignore next */
    function onError(thisErr) {
      running--;
      err = err || thisErr;
      doNext();
    }

    function runNextBatch() {
      while (running < limit && current < len) {
        runNext();
      }
    }

    runNextBatch();
  });
}
954933
def acquire(self, timeout=None):
        

        timeout = timeout is not None and timeout or self.timeout
        end_time = time.time()
        if timeout is not None and timeout > 0:
            end_time += timeout

        while True:
            try:
                write_pid_to_pidfile(self.path)
            except OSError as exc:
                if exc.errno == errno.EEXIST:
                    # The lock creation failed.  Maybe sleep a bit.
                    if timeout is not None and time.time() > end_time:
                        if timeout > 0:
                            raise LockTimeout("Timeout waiting to acquire"
                                              " lock for %s" %
                                              self.path)
                        else:
                            raise AlreadyLocked("%s is already locked" %
                                                self.path)
                    time.sleep(timeout is not None and timeout/10 or 0.1)
                else:
                    raise LockFailed("failed to create %s" % self.path)
            else:
                return
181132
protected function __tryLock()
    {
        return PoolManager::use($this->poolName, function($resource, $redis){
            return 1 == $redis->evalEx(<<<SCRIPT
local key     = KEYS[1]
local content = KEYS[2]
local ttl     = ARGV[2]
local db      = ARGV[1]
redis.call('select', db)
local lockSet = redis.call('setnx', key, content)
if lockSet == 1 then
redis.call('pexpire', key, ttl)
else 
local value = redis.call('get', key)
if(value == content) then
lockSet = 1;
redis.call('pexpire', key, ttl)
end
end
return lockSet
SCRIPT
            , [
                $this->key,
                $this->guid,
                $this->db,
                $this->lockExpire,
            ], 2);
        });
    }
1213984
def acquire(self):
        
        while self.size() == 0 or self.size() < self._minsize:
            _conn = yield from self._create_new_conn()
            if _conn is None:
                break
            self._pool.put_nowait(_conn)

        conn = None
        while not conn:
            _conn = yield from self._pool.get()
            if _conn.reader.at_eof() or _conn.reader.exception():
                self._do_close(_conn)
                conn = yield from self._create_new_conn()
            else:
                conn = _conn

        self._in_use.add(conn)
        return conn
93245
function(pool) {
    if (
      !connectionInCreation &&
      pool.idleConnections() < opts.minimumIdle &&
      pool.totalConnections() < opts.connectionLimit &&
      !closed
    ) {
      connectionInCreation = true;
      process.nextTick(() => {
        const timeoutEnd = Date.now() + opts.initializationTimeout;
        if (!closed) {
          connectionCreationLoop(pool, 0, timeoutEnd)
            .then(conn => {
              if (closed) {
                return conn.forceEnd().catch(err => {});
              }
              addPoolConnection(pool, conn);
            })
            .catch(err => {
              if (pool.totalConnections() === 0) {
                const task = taskQueue.shift();
                if (task) {
                  firstTaskTimeout = clearTimeout(firstTaskTimeout);
                  process.nextTick(task.reject, err);
                  resetTimeoutToNextTask();
                }
              } else if (!closed) {
                console.error(
                  `pool fail to create connection (${err.message})`
                );
              }

              //delay next try
              setTimeout(() => {
                connectionInCreation = false;
                if (taskQueue.size() > 0) {
                  ensurePoolSize(pool);
                }
              }, 500);
            });
        }
      });
    }
  }
1353223
def _create_connection_pool(self, conn_params):
    '''
    
    '''
    connection_pools_lock.acquire()
    try:
        # One more read to prevent a read/write race condition (We do this
        # here to avoid the overhead of locking each time we get a connection.)
        if (self.alias not in connection_pools or
            connection_pools[self.alias]['settings'] != self.settings_dict):
            logger.info("Creating connection pool for db alias %s" % self.alias)
            logger.info("  using MIN_CONNS = %s, MAX_CONNS = %s, TEST_ON_BORROW = %s" % (self._min_conns,
                                                                                         self._max_conns,
                                                                                         self._test_on_borrow))

            from psycopg2 import pool
            connection_pools[self.alias] = {
                'pool': pool.ThreadedConnectionPool(self._min_conns, self._max_conns, **conn_params),
                'settings': dict(self.settings_dict),
            }
    finally:
        connection_pools_lock.release()
79491
def init_pool(self):
        """"""

        # initialize the pool if needed
        if self.pool is None:
            if self.nproc > 1:
                self.pool = mp.Pool(processes=self.nproc)
            else:
                self.pool = None
        else:
            print('pool already initialized?')
883923
def _lock(self, timeout_ms=-1):
        """"""
        vbox = VirtualBox()
        machine = vbox.find_machine(self.machine_name)
        wait_time = 0
        while True:
            session = Session()
            try:
                machine.lock_machine(session, LockType.write)
            except Exception as exc:
                if timeout_ms != -1 and wait_time > timeout_ms:
                    raise ValueError("Failed to acquire lock - %s" % exc)
                time.sleep(1)
                wait_time += 1000
            else:
                try:
                    yield session
                finally:
                    session.unlock_machine()
                break
731606
def create_thread(*args)
      return if pool_closed?
      thread = nil
      @lock.synchronize do
        if(args.include?(:nowait) || action_size > size || action_size > waiting || args.include?(:force))
          if(size < max || args.include?(:force))
            thread = ActionPool::Thread.new(:pool => self, :respond_thread => @respond_to,
              :a_timeout => @action_timeout, :t_timeout => @thread_timeout, :logger => @logger,
              :autostart => false)
            @threads << thread
          end
        end
        if(((size == working || args.include?(:nowait)) && @threads.size < @max_threads) || args.include?(:force))

        end
      end
      thread.start if thread
      thread
    end