Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get CancelledKeyException when going through the keys?

Why do I get the CancelledKeyException few times a day? Should I do something about it? Is my code wrong?

        Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
        while (keys.hasNext()) {

            SelectionKey key = (SelectionKey) keys.next();
            keys.remove();

            try {
                if (key.isValid()) {
                    if (key.isReadable()) {
                        readHandler.handle((Connection) key.attachment());
                    }
                    if (key.isWritable()) {
                        writeHandler.handle((Connection) key.attachment());
                    }
                    if (key.isAcceptable()) {
                        acceptHandler.handle(key);
                    }
                }
            } catch (CancelledKeyException e) {
                _logger.error("CanceledKeyException in while loop:", e);
            }
        }

Exception:

java.nio.channels.CancelledKeyException: null
    at sun.nio.ch.SelectionKeyImpl.ensureValid(SelectionKeyImpl.java:55) ~[na:1.6.0_12]
    at sun.nio.ch.SelectionKeyImpl.readyOps(SelectionKeyImpl.java:69) ~[na:1.6.0_12]
    at java.nio.channels.SelectionKey.isWritable(SelectionKey.java:294) ~[na:1.6.0_12]
    at project.engine.io.SimpleReactor.work(SimpleReactor.java:194) ~[engine-02.06.11.jar:na]
    at project.server.work.AbstractWorker$1.run(AbstractWorker.java:20) [server-21.05.11.jar:na]
    at java.lang.Thread.run(Thread.java:619) [na:1.6.0_12]
like image 766
Rihards Avatar asked Jun 02 '11 13:06

Rihards


1 Answers

One of the handlers may close the channel. For example, the read handler should close the channel if it reads a -1. So the write handler will then fail. Indeed isWritable() will fail, as I can now see from your stack trace. So you must test isValid() with every other condition, e.g. isValid() && isReadable(), isValid() && isWritable(), etc.

like image 121
user207421 Avatar answered Nov 16 '22 00:11

user207421