How can I / O multiplexing be used to process requests asynchronously in a java server?
Suppose I'm writing a java server that communicates with clients over TCP / IP
The server uses I / O multiplexing There is a separate thread t0 that waits for the selector and handles client connections For example, if the connection is ready for reading, t0 will read data from the connection
Suppose the server has read the incoming request and is now ready to process it Since processing takes time, the request is processed in another thread T1, and t0 returns to the wait selector
Suppose T1 has finished processing and created a response T0 should now start writing the response to the client connection So my question is: how does T1 send a response to t0?
Solution
The same thread T1 should read, process, and return the result to the client
Here is an overview of how to use the Java NiO API to complete it without linking the number of threads to the number of clients
**//Thread T0** //wait for selection keys ... Iterator it = selector.selectedKeys().iterator( ); while (it.hasNext( )) { SelectionKey key = (SelectionKey) it.next(); // Is a new connection coming in? if (key.isAcceptable( )) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel channel = server.accept() // Set the new channel nonblocking channel.configureBlocking (false); // Register it with the selector channel.register (selector,SelectionKey.OP_READ); } // Is there data to read on this channel? if (key.isReadable( )) { processRequest (key); } it.remove( ); } ... ExecutorService service = Executors.newFixedThreadPool(50); ... void processRequest(final SelectionKey key) { **//Thread T1-T50** //deal with request executorService.submit(new Runnable() { SocketChannel channel = (SocketChannel) key.channel(); //read data from channel,process it and write back to the channel. }); ) }