NIO Selector activating immediately and not blocking on select(). Spinning through loop uncontrollably
I have a selector thread: http://www.copypastecode.com/83442/
It has a list of ChangeRequests it processes, then blocks, then processes Keys. The methods connect and send are the only ones sending wakeup() to the selector.
When I establish 2 Servers and run separate select loops, it happens that the 2nd server doesn't seem to block on select(). I say this because no log message get printed, either in connect or send, no in the processing of keys. When infinitely looping, no keys are being processed.
How can I fix this situation? If defeats the purpose of using non-blocking IO.
protected void startSelectorThread() {
new Thread() {
public void run() {
log.debug("NIOThreadedConnection: Selector Thread started; " + serverSocketChannel);
selectorRunning = true;
开发者_如何学C while (selectorRunning == true) {
log.debug(".");
processChangeRequests();
blockForSelectorTraffic();
processSelectionKeys();
}
System.out.println("Selector Thread terminated");
nioServer.stoppedListening(null);
}
}.start();
}
protected void processChangeRequests() {
synchronized (pendingChanges) {
for(ChangeRequest change:pendingChanges) {
switch (change.type) {
case ChangeRequest.CHANGEOPS: {
SelectionKey key = change.socket.keyFor(socketSelector);
if (key == null) {
continue;
}
key.interestOps(change.ops);
continue;
}
// Client only:
case ChangeRequest.REGISTER: {
try {
log.debug("future connection with channel: " + change.socket);
change.socket.register(socketSelector, change.ops);
} catch (ClosedChannelException e) {
log.debug("closed channel(" + change.socket + ")");
}
continue;
}
}
}
pendingChanges.clear();
}
}
protected void blockForSelectorTraffic() {
try {
socketSelector.select();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void processSelectionKeys() {
Iterator<SelectionKey> selectedKeys = socketSelector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey key = selectedKeys.next();
log.debug("found a key: " + key);
selectedKeys.remove();
if (!key.isValid()) {
log.debug("key invalid: " + key);
continue;
}
try {
if (key.isAcceptable()) {
log.debug("accept with a ListenConnection: " + key);
try {
accept(key);
} catch (ClosedChannelException e) {
log.debug("closed server channel(" + key + ")");
}
} else if (key.isConnectable()) {
log.debug("finishing connection: " + key);
finishConnection(key);
} else if (key.isReadable()) {
log.debug("reading with key: " + key);
int bytesRead = read(key);
log.debug("read: " + bytesRead + " with key: " + key);
} else if (key.isWritable()) {
log.debug("writing with key: " + key);
int bytesWritten = write(key);
log.debug("write: " + bytesWritten + " with key: " + key);
}
} catch (IOException e) {
e.printStackTrace();
}
}
log.debug("all done with keys");
}
Thanks, Robert
精彩评论