Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are selectors implemented internally?

Tags:

java

nio

I've just started exploring java NIO, non-blocking IO. I'm interested to know the fundamentals behind the implementation. How is communication between Java selector and physical socket is established? Is there a operating system level thread that polls underlying resource continuously? And is there any java thread per selector continously polling to receive these events? Can someone of you kindly point me to this.

like image 652
Gopal Avatar asked Aug 29 '11 11:08

Gopal


3 Answers

No, the point of select is that you don't have to waste cycles polling when nothing is happening. Every OS implements this capability in some way or other (usually through hardware interrupts) and makes it available to user-space programs through the select() system call. The connection to the Java language is that the JVM now contains code that will call the OS's select for you if you use the right NIO classes and methods. But this required changes to the JVM code itself, it isn't something that you could have done purely within Java before NIO.

like image 195
Kilian Foth Avatar answered Nov 11 '22 15:11

Kilian Foth


Since it is not specified in the documentation, I'd assume that (strictly speaking) this is implementation dependent.

However in *NIX and Windows the implementation typically relies directly on the select system call. This system call is not implemented by spawning multiple threads.

like image 25
aioobe Avatar answered Nov 11 '22 17:11

aioobe


It depends on the operation system used. On Linux the current implementation use's the kernel's epoll mechanism.

Typically the underlying kernel network system is filling or draining buffers for the socket, probably on it's IRQ handling threads. So what you are waiting for is the kernel to tell you that a buffer is ready to be filled (writing) or read to be draining (reading).

like image 3
Michael Barker Avatar answered Nov 11 '22 15:11

Michael Barker