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

81 views Asked by At

The code from below shows a small chunk of code which tries to accept the incomming connections from clients (typical implementation with java NIO), but when I try to remove the SelectionKey from the Iterator, it throws that exception.

This code looks very similar with 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()
  }
1

There are 1 answers

0
Alan Bateman On BEST ANSWER

The selected-key set is returned by selector.selectedKey (you have selector.keys which is the specified to be unmodifiable)