Selector NonBlocking Example
This program demonstrates non blocking select using Selector.
Problem Statement
Write a Java program that checks channels without blocking using Selector.selectNow().
Source Code
| 1 | import java.net.*; |
| 2 | import java.nio.*; |
| 3 | import java.nio.channels.*; |
| 4 | import java.util.*; |
| 5 | public class SelectorNonBlockingExample { |
| 6 | public static void main(String[] args) throws Exception { |
| 7 | System.out.println("Eduinq Selector NonBlocking Example"); |
| 8 | Selector selector=Selector.open(); |
| 9 | SocketChannel sc=SocketChannel.open(new InetSocketAddress("localhost",5000)); |
| 10 | sc.configureBlocking(false); |
| 11 | sc.register(selector,SelectionKey.OP_READ); |
| 12 | int ready=selector.selectNow(); |
| 13 | System.out.println("Eduinq Ready Channels: "+ready); |
| 14 | sc.close(); selector.close(); |
| 15 | } |
| 16 | } |
Program Output
Eduinq Selector NonBlocking Example Eduinq Ready Channels: 0
Explanation
Uses selector.selectNow() for immediate check. - Returns count of ready channels. - Exception handling ensures safe operations. - In enterprise systems, non blocking select supports responsive servers. Conclusion: Shows non blocking select.