Hold twenty thousand mostly idle sensors on one selector
Hold twenty thousand mostly idle sensors on one selector
Answer
Selector selector = Selector.open(); for (SocketChannel sensor : sensors) { // 20,000 of them sensor.configureBlocking(false); sensor.register(selector, SelectionKey.OP_READ); } System.out.println(selector.keys().size() + " connections, one thread");
This is the telemetry collector from the worked example, and it is the only one of the three servers that needed NIO. Each registration costs a `SelectionKey` — a few hundred bytes — where thread-per-connection would have reserved a stack, so the same 20,000 connections go from roughly 20 GB of address space to a few megabytes. The rest of this module is what the loop after these six lines has to look like.
JDK javadoc java.nio.channels.Selector; java.nio.channels.SelectionKey