How do you use Selector with a simple code example?

In Java, a Selector is used to multiplex I/O operations, allowing a single thread to manage multiple channels (like sockets). This is particularly useful in network applications where you want to handle many connections efficiently.

Example of Using Selector

import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SelectableChannel; import java.util.Iterator; public class SelectorExample { public static void main(String[] args) throws IOException { Selector selector = Selector.open(); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.bind(new InetSocketAddress(5000)); serverSocketChannel.configureBlocking(false); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { selector.select(); Iterator keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = keys.next(); keys.remove(); if (key.isAcceptable()) { SocketChannel clientChannel = serverSocketChannel.accept(); // Handle new client connection } } } } }

Selector Java NIO multiplexing I/O operations network applications