I am currently trying to operate a SocketChannel from one thread (I previously achieved what I wanted to do with two thread and regular sockets, but two threads per client seemed a little excessive). I want to be able to read when there is data to read (selector works fine for that). I only want to write when there are items in a blocking queue (in my example, I have frame queue).
@Override
public void run() {
super.run();
SelectionKey readKey = null;
try {
final int interests = SelectionKey.OP_READ;
socketChannel.configureBlocking(false);
readKey = socketChannel.register(selector, interests);
} catch (IOException e) {
e.printStackTrace();
try {
close();
} catch (Exception e1) {
throw new RuntimeException("FAILURE");
}
}
if (null != readKey) {
while (running) {
try {
System.out.println("LOOP ENTRY");
selector.select();
if (readKey.isReadable()) {
System.out.println("IS READABLE");
}
if (readKey.isWritable() && (null != framesQueues.peek())) {
System.out.println("IS WRITEABLE");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Now, what it does is, it loops furiously without stopping, and that's obviously bad. I'm looking for a way I could have my selector wakeup when there is an item in my blocking queue, or when there are bytes to read. Is there a tooling in NIO that allows that?
If not, what could I implement? Am I doomed of using two threads per client? It's for a hobby project, but I'm trying to achieve as low latency as possible, so looping with a sleep is not what I want.