Video tayyorlanmoqda

Strong Middle 📁 IO va NIO

NIO Selector qanday ishlaydi va bitta thread minglab ulanishga qanday xizmat qiladi?

Barcha SocketChannel'lar non-blocking rejimga o'tkazilib, bitta Selector'ga ro'yxatdan o'tadi. select() OS'dan (Linux'da epoll) qaysi channel'lar o'qish yoki yozishga tayyor ekanini so'raydi va thread faqat tayyorlari bilan ishlaydi — hech qachon bitta sekin klientni kutib qolmaydi.

📖 Javob

Klassik model: bitta ulanish — bitta thread, thread read()'da bloklanib turadi. 10 000 ulanish = 10 000 thread, har biri stack uchun xotira oladi.

Selector modeli:

Selector sel = Selector.open();
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(8080));
server.configureBlocking(false);
server.register(sel, SelectionKey.OP_ACCEPT);

while (true) {
    sel.select();
    Iterator<SelectionKey> it = sel.selectedKeys().iterator();
    while (it.hasNext()) {
        SelectionKey key = it.next();
        it.remove();                              // o'zingiz olib tashlashingiz shart
        if (key.isAcceptable()) {
            SocketChannel c = server.accept();
            c.configureBlocking(false);
            c.register(sel, SelectionKey.OP_READ, ByteBuffer.allocate(4096));
        } else if (key.isReadable()) {
            SocketChannel c = (SocketChannel) key.channel();
            ByteBuffer buf = (ByteBuffer) key.attachment();
            if (c.read(buf) == -1) { key.cancel(); c.close(); }
        }
    }
}

Murakkab joylari:

  • read xabarning bir qismini qaytarishi mumkin — har bir ulanish uchun holat (attachment) saqlab, xabar chegarasini o'zingiz topasiz;
  • write ham hammasini yozmasligi mumkin; qoldiq bo'lsa OP_WRITE'ga obuna bo'lasiz, yozib bo'lgach olib tashlaysiz. OP_WRITE'ni doim yoqib qo'ysangiz, CPU 100% ga chiqadi;
  • event loop ichida bloklovchi ish (DB so'rov) qilinmaydi — u barcha ulanishlarni to'xtatadi.

Shu sababli amalda xom Selector bilan kam yozishadi: Netty, Undertow, Reactor Netty buni to'g'ri qilib bergan.