1

I have been getting Getting java.nio.channels.CancelledKeyException thrown from:

at sun.nio.ch.SelectionKeyImpl.ensureValid(SelectionKeyImpl.java:55)
at sun.nio.ch.SelectionKeyImpl.interestOps(SelectionKeyImpl.java:64)

However, I am not calling the java.nio.channels.SelectionKey.cancel() explicitly at any point.

An important piece of information is that this is happening in my testing environment which runs on EC2 and there is communication going on between multiple machines where I kill processes in the machines which are target for communication abruptly. However, I could not correlate this exception time of appearance to any initiated process termination. Could this happen if the underlying socket is disconnected or there are network connectivity issues?

Thanks

Nicholas
  • 7,403
  • 10
  • 48
  • 76
Eitan
  • 494
  • 5
  • 10

1 Answers1

1

A key is cancelled automatically when the underlying channel is closed. You should check for valid keys while iterating the selectedKeys, and if your event handlers can close the channel, as they should in at least the case of the read handler, you should check for key validity before calling interestOps(), isWritable(), etc.

user207421
  • 305,947
  • 44
  • 307
  • 483