Women in Technology

Hear us Roar



Article:
  Building Highly Scalable Servers with Java NIO
Subject:   Danger else case in main thread
Date:   2008-01-23 12:58:11
From:   jolpe
Hi!
Some comment about this part of the main thread code.



if (sk.isAcceptable()) {
// A connection is ready to be completed
((AcceptSelectorHandler)handler).
handleAccept();

} else if (sk.isConnectable()) {
// A connection is ready to be accepted
((ConnectorSelectorHandler)handler).
handleConnect();

} else {
ReadWriteSelectorHandler rwHandler =
(ReadWriteSelectorHandler)handler;
// Readable or writable
if (sk.isReadable()) {
// It is possible to read
rwHandler.handleRead();
}

// Check if the key is still valid,
// since it might have been invalidated
// in the read handler (for instance,
// the socket might have been closed)
if (sk.isValid() && sk.isWritable()) {
// It is read to write
rwHandler.handleWrite();
}

You should avoid the else cases when detecting kind of key . The keys may be mixed. For example key value 5 contains both write and read.


If you use else you may miss key events. For example if two events connect and read are mixed. Only connect will be executed.


Learned the hard way...


Regards
Mattias