Queues a node for asynchronous connection during the next .poll()
19617
def maybe_connect(self, node_id, wakeup=True):
        """"""
        if self._can_connect(node_id):
            self._connecting.add(node_id)
            # Wakeup signal is useful in case another thread is
            # blocked waiting for incoming network traffic while holding
            # the client lock in poll().
            if wakeup:
                self.wakeup()
            return True
        return False
713537
protected void sendNextPing() {
		Set<String> nodeIDs = transporter.getAllNodeIDs();

		// Remove this node's ID
		nodeIDs.remove(nodeID);

		// Remove duplications by IP address
		int size = nodeIDs.size() * 2;
		HashSet<String> ips = new HashSet<>(size);
		Iterator<String> i = nodeIDs.iterator();
		while (i.hasNext()) {
			Tree descriptor = transporter.getDescriptor(i.next());
			if (descriptor == null) {
				continue;
			}
			Tree ipList = descriptor.get("ipList");
			if (ipList == null) {
				continue;
			}
			for (Tree ip : ipList) {
				if (ip == null) {
					continue;
				}
				String value = ip.asString();
				if (value == null || value.startsWith("127.")) {
					continue;
				}
				if (ips.contains(value)) {
					i.remove();
					break;
				}
				ips.add(value);
			}
			try {
				Thread.sleep(5);
			} catch (InterruptedException interrupt) {
				return;
			}
		}

		// Has peers?
		if (nodeIDs.isEmpty()) {
			return;
		}

		// Find the next nodeID
		boolean submitted = false;
		if (previousNodeID != null) {
			boolean found = false;
			for (String nextNodeID : nodeIDs) {
				if (previousNodeID.equals(nextNodeID)) {
					found = true;
					continue;
				}
				if (found && !nodeID.equals(nextNodeID)) {

					// Send PING to the next node
					submitted = true;
					previousNodeID = nextNodeID;
					sendPing(nextNodeID);
					break;
				}
			}
		}

		// Send PING to the first node
		if (!submitted) {
			for (String nextNodeID : nodeIDs) {
				if (!nodeID.equals(nextNodeID)) {
					previousNodeID = nextNodeID;
					sendPing(nextNodeID);
					break;
				}
			}
		}
	}
996459
def polling_loop(connection)
      if polling?
        polling_msg = "Polling enabled. Checking every #{config.poll_interval} seconds."
      else
        polling_msg = "Polling disabled. Checking for messages once."
      end
      Mailman.logger.info(polling_msg)

      tries ||= 5
      loop do
        begin
          connection.connect
          connection.get_messages
        rescue SystemCallError, EOFError => e
          Mailman.logger.error e.message
          unless (tries -= 1).zero?
            Mailman.logger.error "Retrying..."
            begin
              connection.disconnect
            rescue # don't crash in the crash handler
            end
            retry
          end
        ensure
          connection.started? && connection.disconnect
        end

        break unless polling?
        sleep config.poll_interval
      end
    end
582942
private void handleInputQueue() {
    if (!addedQueue.isEmpty()) {
      getLogger().debug("Handling queue");
      Collection<MemcachedNode> toAdd = new HashSet<MemcachedNode>();
      Collection<MemcachedNode> todo = new HashSet<MemcachedNode>();

      MemcachedNode qaNode;
      while ((qaNode = addedQueue.poll()) != null) {
        todo.add(qaNode);
      }

      for (MemcachedNode node : todo) {
        boolean readyForIO = false;
        if (node.isActive()) {
          if (node.getCurrentWriteOp() != null) {
            readyForIO = true;
            getLogger().debug("Handling queued write %s", node);
          }
        } else {
          toAdd.add(node);
        }
        node.copyInputQueue();
        if (readyForIO) {
          try {
            if (node.getWbuf().hasRemaining()) {
              handleWrites(node);
            }
          } catch (IOException e) {
            getLogger().warn("Exception handling write", e);
            lostConnection(node);
          }
        }
        node.fixupOps();
      }
      addedQueue.addAll(toAdd);
    }
  }
764259
function () {
    var self = this;
    if (self._pollsScheduledButNotStarted > 0)
      return;
    ++self._pollsScheduledButNotStarted;
    self._taskQueue.queueTask(function () {
      self._pollMongo();
    });
  }
1372829
@Override
	public E poll() {
		E e = queue.poll();
		if (e != null){
			signalSizeReduced();
		}
		return e;
	}
303598
async def wait_nodes(self, timeout, check_ready=True):
        
        return await self.wait_slaves(timeout, check_ready=check_ready)
636242
def connect_async(self, conn_id, connection_string, callback):
        """"""

        future = self._loop.launch_coroutine(self._adapter.connect(conn_id, connection_string))
        future.add_done_callback(lambda x: self._callback_future(conn_id, x, callback))
941480
def wait(self, seconds=None, **kw):
        ''
        # Use ping/pong to unblock recv for polling transport
        self._heartbeat_thread.hurry()
        # Use timeout to unblock recv for websocket transport
        self._transport.set_timeout(seconds=1)
        # Listen
        warning_screen = self._yield_warning_screen(seconds)
        for elapsed_time in warning_screen:
            if self._should_stop_waiting(**kw):
                break
            try:
                try:
                    self._process_packets()
                except TimeoutError:
                    pass
                except KeyboardInterrupt:
                    self._close()
                    raise
            except ConnectionError as e:
                self._opened = False
                try:
                    warning = Exception('[connection error] %s' % e)
                    warning_screen.throw(warning)
                except StopIteration:
                    self._warn(warning)
                try:
                    namespace = self.get_namespace()
                    namespace._find_packet_callback('disconnect')()
                except PacketError:
                    pass
        self._heartbeat_thread.relax()
        self._transport.set_timeout()
541984
public void async() {
		final Request request = data.build();
		final CallbackHandler handler = request.handler != null ? request.handler : singleton.handler;
		final boolean safe = request.safe != null ? request.safe : singleton.safe;

		// Ignore current request if already running (ignoreIfRunning)
		synchronized (activeRequests) {
			if (ignoreIfRunning && activeRequests.contains(request.tag)) {
				singleton.log(request.tag + " request already running! Ignoring...");
				return;
			}
			activeRequests.add(request.tag);
		}

		new AsyncTask<Void, Void, Void>() {
			@Override
			protected Void doInBackground(Void... params) {
				try {
					// Delay thread if specified
					if (delay > 0) {
						singleton.log("Delaying " + request.tag + " request for " + delay + "ms");
						Thread.sleep(delay);
					}

					// Execute request
					try {
						singleton.load(request);
					} catch (IOException e) {
						singleton.log("Error executing request " + request.tag + " asynchronously! " + e.getMessage(), Log.ERROR);
						handler.onLoadFailed(safe, request.callback.get());
					}
				} catch (InterruptedException e) {
					singleton.log(request.tag + " thread interrupted!");
				} finally {
					synchronized (activeRequests) {
						activeRequests.remove(request.tag);
					}
				}
				return null;
			}

			@Override
			protected void onCancelled(Void aVoid) {
				super.onCancelled(aVoid);

				// Double check to make sure this request is removed
				synchronized (activeRequests) {
					activeRequests.remove(request.tag);
				}
			}
		}.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
	}
1179476
private void returnConnection(final ConnectionHolder connectionHolder) {

        ClientStatistics stats = connectionHolder.clientConnection.getStatistics();
        this.requestCount.incrementAndGet();
        if(stats != null) {
            //we update the stats when the connection is closed
            this.read.addAndGet(stats.getRead());
            this.written.addAndGet(stats.getWritten());
            stats.reset();
        }

        HostThreadData hostData = getData();
        if (closed) {
            //the host has been closed
            IoUtils.safeClose(connectionHolder.clientConnection);
            ConnectionHolder con = hostData.availableConnections.poll();
            while (con != null) {
                IoUtils.safeClose(con.clientConnection);
                con = hostData.availableConnections.poll();
            }
            redistributeQueued(hostData);
            return;
        }

        //only do something if the connection is open. If it is closed then
        //the close setter will handle creating a new connection and decrementing
        //the connection count
        final ClientConnection connection = connectionHolder.clientConnection;
        if (connection.isOpen() && !connection.isUpgraded()) {
            CallbackHolder callback = hostData.awaitingConnections.poll();
            while (callback != null && callback.isCancelled()) {
                callback = hostData.awaitingConnections.poll();
            }
            if (callback != null) {
                if (callback.getTimeoutKey() != null) {
                    callback.getTimeoutKey().remove();
                }
                // Anything waiting for a connection is not expecting exclusivity.
                connectionReady(connectionHolder, callback.getCallback(), callback.getExchange(), false);
            } else {
                final int cachedConnectionCount = hostData.availableConnections.size();
                if (cachedConnectionCount >= maxCachedConnections) {
                    // Close the longest idle connection instead of the current one
                    final ConnectionHolder holder = hostData.availableConnections.poll();
                    if (holder != null) {
                        IoUtils.safeClose(holder.clientConnection);
                    }
                }
                hostData.availableConnections.add(connectionHolder);
                // If the soft max and ttl are configured
                if (timeToLive > 0) {
                    //we only start the timeout process once we have hit the core pool size
                    //otherwise connections could start timing out immediately once the core pool size is hit
                    //and if we never hit the core pool size then it does not make sense to start timers which are never
                    //used (as timers are expensive)
                    final long currentTime = System.currentTimeMillis();
                    connectionHolder.timeout = currentTime + timeToLive;
                    if(hostData.availableConnections.size() > coreCachedConnections) {
                        if (hostData.nextTimeout <= 0) {
                            hostData.timeoutKey = WorkerUtils.executeAfter(connection.getIoThread(), hostData.timeoutTask, timeToLive, TimeUnit.MILLISECONDS);
                            hostData.nextTimeout = connectionHolder.timeout;
                        }
                    }
                }
            }
        } else if (connection.isOpen() && connection.isUpgraded()) {
            //we treat upgraded connections as closed
            //as we do not want the connection pool filled with upgraded connections
            //if the connection is actually closed the close setter will handle it
            connection.getCloseSetter().set(null);
            handleClosedConnection(hostData, connectionHolder);
        }
    }
947120
private AsyncResourceRequest<V> getNextUnexpiredResourceRequest(Queue<AsyncResourceRequest<V>> requestQueue) {
        AsyncResourceRequest<V> resourceRequest = requestQueue.poll();
        while(resourceRequest != null) {
            if(resourceRequest.getDeadlineNs() < System.nanoTime()) {
                resourceRequest.handleTimeout();
                resourceRequest = requestQueue.poll();
            } else {
                break;
            }
        }
        return resourceRequest;
    }
881168
function reportUnnecessaryAwait(node) {
            context.report({
                node: context.getSourceCode().getFirstToken(node),
                loc: node.loc,
                message
            });
        }
672000
private void setHead(Node node) {
        head = node;
        node.thread = null;
        node.prev = null;
    }
1146735
void afterRead(Node<K, V> node) {
        final int bufferIndex = readBufferIndex();
        final long writeCount = recordRead(bufferIndex, node);
        drainOnReadIfNeeded(bufferIndex, writeCount);
        notifyListener();
    }
579152
@Override
    public final T poll(final long timeout, final TimeUnit unit) throws InterruptedException {
        final long start = getWriteLockWithOptionalWait(timeout, unit);
        if (start == Long.MIN_VALUE) {
            // Min value signals a timeout while waiting
            return null;
        }
        final long maxWait = start >= 0 ? unit.toMillis(timeout) : -1;

        try {
            // Wait for an element to be available to return
            if (!this.waitForAdd(start, maxWait)) {
                return null;
            }

            return this.pollInternal(false);
        } finally {
            this.writeLock.unlock();
        }
    }
963486
private void finishConnect(final SelectionKey sk, final MemcachedNode node)
    throws IOException {
    if (verifyAliveOnConnect) {
      final CountDownLatch latch = new CountDownLatch(1);
      final OperationFuture<Boolean> rv = new OperationFuture<Boolean>("noop",
        latch, 2500, listenerExecutorService);
      NoopOperation testOp = opFact.noop(new OperationCallback() {
        public void receivedStatus(OperationStatus status) {
          rv.set(status.isSuccess(), status);
        }

        @Override
        public void complete() {
          latch.countDown();
        }
      });

      testOp.setHandlingNode(node);
      testOp.initialize();
      checkState();
      insertOperation(node, testOp);
      node.copyInputQueue();

      boolean done = false;
      if (sk.isValid()) {
        long timeout = TimeUnit.MILLISECONDS.toNanos(
          connectionFactory.getOperationTimeout());

        long stop = System.nanoTime() + timeout;
        while (stop > System.nanoTime()) {
          handleWrites(node);
          handleReads(node);
          if(done = (latch.getCount() == 0)) {
            break;
          }
        }
      }

      if (!done || testOp.isCancelled() || testOp.hasErrored()
        || testOp.isTimedOut()) {
        throw new ConnectException("Could not send noop upon connect! "
          + "This may indicate a running, but not responding memcached "
          + "instance.");
      }
    }

    connected(node);
    addedQueue.offer(node);
    if (node.getWbuf().hasRemaining()) {
      handleWrites(node);
    }
  }