尝试从迭代器中删除 SelectionKey 时抛出 UnsupportedOperationException

UnsupportedOperationException is throwed when try to remove the SelectionKey from the iterator

下面的代码显示了一小段代码,它试图接受来自客户端的传入连接(使用 java NIO 的典型实现),但是当我尝试从迭代器中删除 SelectionKey 时,它会抛出那个例外。

此代码看起来与 Jenkov tutorial and this other one Acceptor (line 270) SocketServer from Apache Kafka 非常相似。

  override def run(): Unit = {

    this.logger.info("Acceptor started.")

    super.run()

    this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT)

    while (this.isRunning) {

      val readyKeys = this.selector.select(500)

      if (readyKeys > 0) {

        val selectedKeys = this.selector.keys()

        val selectionKeysIterator = selectedKeys.iterator()

        while (selectionKeysIterator.hasNext && this.isRunning) {

          val selectionKey = selectionKeysIterator.next()

          selectionKeysIterator.remove()

          if (!selectionKey.isAcceptable)
            throw new IllegalStateException("The SelectionKey is not on the valid state [Acceptable].")

          this.accept(selectionKey)
        }
      }
    }

    this.selector.close()
  }

选择键集由selector.selectedKey返回(你有selector.keys指定为不可修改)