~/ learn/ comp-348/ cards/ Non-blocking I/O
1 of 25

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

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/70c5564f-18af-4b1b-931e-525a439d9359/flashcard utf-8 LF