Ashwin
Ashwin

Reputation: 13547

How does asynchrounous NIO from JDK work?

In the JVM, threads are just thin wrappers around native OS threads. And native OS threads have a high footprint and creating them/switching between them is not a lightweight task. To overcome this downside the asynchronous NIO in JDK was brought in which returns the thread to the thread pool while the task is waiting. Once the task is over, another thread from the thread pool is picked up to carry on the task.
How does the system know that the task is over? The task could be waiting for a response from an HTTP server. But since the thread has been returned to the thread pool, who interrupts the CPU to notify that the task is done and the work can be continued?

Upvotes: 2

Views: 85

Answers (1)

pveentjer
pveentjer

Reputation: 11402

Threads are not returned to the thread pool.

If you are referring to Selectors then you have a single thread that can serve many connections. This is called multiplexed IO and on Linux the Linux epoll system is under the hood. This thread is your own to control.

So your thread runs in some event loop over the selector. It will wait if there is nothing ready (e.g. data available for reading in a socket) and once the data comes in, the selector will wakeup the thread, and the thread can then deal with every selection key that is ready for processing.This way a single thread can process a bunch of connections concurrently.

Pseudo code:

for(;;){
   int count = selector.select();
   if(count>0){
       for(SelectionKey key: selector.getReadySet()){
         process(key);
       }
   }
}

And the above loop you run in your own thread.

Upvotes: 1

Related Questions