Exemplo n.º 1
0
  /** Polls through all available channels and returns those that are ready. */
  @Override
  public int selectNow() throws IOException {
    UDPSocketChannel[] array = _channels;
    UDPSocketChannel[] removed = null;

    selectedKeys.clear();

    for (int i = 0; i < array.length; i++) {
      UDPSocketChannel channel = array[i];
      if (channel == null) continue;

      UDPSelectionKey key = (UDPSelectionKey) channel.keyFor(this);
      if (key != null) {
        if (key.isValid() && channel.isOpen()) {
          int currentOps = channel.getProcessor().readyOps();
          int readyOps = currentOps & key.interestOps();
          if (readyOps != 0) {
            key.setReadyOps(readyOps);
            selectedKeys.add(key);
          }
        } else {
          if (removed == null) removed = new UDPSocketChannel[array.length];
          removed[i] = channel;
        }
      }
    }

    // Go through the removed list & remove them from _connections.
    // _connections may have changed (since we didn't lock while polling),
    // so we need to check and ensure the given UDPConnectionProcessor
    // is the same.
    synchronized (this) {
      if (removed != null) {
        UDPSocketChannel[] copy = new UDPSocketChannel[_channels.length];
        for (int i = 0; i < _channels.length; i++) {
          if (_channels[i] == removed[i]) copy[i] = null;
          else copy[i] = _channels[i];
        }
        _channels = copy;
      }

      if (!channelsToRemove.isEmpty()) {
        for (SelectableChannel next : channelsToRemove) {
          UDPSelectionKey key = (UDPSelectionKey) next.keyFor(this);
          key.cancel();
          key.setReadyOps(0);
          selectedKeys.add(key);
        }
        channelsToRemove.clear();
      }
    }

    return selectedKeys.size();
  }