def remove_stale_sockets(self):
        """Removes stale sockets then adds new ones if pool is too small."""
        if self.opts.max_idle_time_seconds is not None:
            with self.lock:
                while (self.sockets and
                       self.sockets[-1].idle_time_seconds() > self.opts.max_idle_time_seconds):
                    sock_info = self.sockets.pop()
                    sock_info.close_socket(ConnectionClosedReason.IDLE)
        while True:
            with self.lock:
                if (len(self.sockets) + self.active_sockets >=
                        self.opts.min_pool_size):
                    # There are enough sockets in the pool.
                    break

            # We must acquire the semaphore to respect max_pool_size.
            if not self._socket_semaphore.acquire(False):
                break
            try:
                sock_info = self.connect()
                with self.lock:
                    self.sockets.appendleft(sock_info)
            finally:
                self._socket_semaphore.release()
Removes stale sockets then adds new ones if pool is too small.
stackoverflow/venv/lib/python3.6/site-packages/pymongo/pool.py