Selector: The key to Java NIO non-blocking IO implementations.
blocking io and nonblocking io:
blocking IO refers to a stream-oriented IO prior to jdk1.4, where the server needs to set up a heap of threads waiting for requests on each request, and the client sends the request, consulting the server whether the thread path corresponds, if not, waiting or being denied, if any, The client thread waits for the request to finish before it resumes execution.
When the concurrency is large, the backend service or client processing data is slow, resulting in a large number of threads waiting, that is, the above blocking.
nonblocking io is either single-threaded or uses only a small number of multithreading, each connection is shared with one thread, and when waiting (no event) the thread resources can be freed up to handle other requests, and the event-driven model is accept/read/ Notification (wake-up) of the main thread allocates resources to handle related events after an event such as write has occurred. Java.nio.channels.Selector is the observer for events in this model, which can register multiple Socketchannel events on a selector, and when no event occurs selector is blocked, when Socketchannel has an accept Wake selector When events such as/read/write occur.
This selector is a single-threaded model used to describe the event-driven model, to optimize performance needs a good threading model to use, the current relatively good NIO framework has netty,apache Mina and so on. The threading model is shared behind this block, which focuses on the blocking and awakening principles of selector.
Let's look at a simple selector code.
selector = Selector.open (); Serversocketchannel SSC = Serversocketchannel.open (); ssc.configureblocking (false); Ssc.socket (). Bind (New Inetsocketaddress (port)); Ssc.register (selector, selectionkey.op_accept); while (true) {//select () blocking, waiting for an event to wake up int Selected = Selector.select (); if (selected > 0) {iterator<selectionkey> selectedkeys = Selector.selectedkeys (). Iterator (); while (Selectedkeys.hasnext ()) {Selectionkey key = Selectedkeys.next (); if (Key.readyops () & selectionkey.op_accept) = = selectionkey.op_accept) {//Handle ACCEPT event} else if ((Key.readyops () & Selectionkey.op_read) = = Selectionkey.op_read) {//Handle READ event} else if ((Key.readyops () & selectionkey.op_write) = = Selectionkey.op_write) {//Handle write Event}selectedkeys.remove ();}}}
Some of the key points in the code are:
Selector.open ();
Selector.select ();
Wake-up after blocking can either have an event occur by registering a socket on the selector or selector.select (timeout) timeout or selector.wakeup () active wakeup;
The whole process of blocking and awakening involves a lot of points, first on a comb out the overall diagram, and then enter the source code will be more easily understood
Now through the OPENJDK in the source code to resolve each of the links:
1. Selector.open ()
Selector.java-----public static Selector open () throws IOException { return Selectorprovider.provider (). Openselector (); }
First Look at what Selectorprovider.provider () has done:
Selectorprovider.java-----Public static Selectorprovider provider () {synchronized (lock) {if (provider! = NULL) Return Provider;return (Selectorprovider) accesscontroller.doprivileged (new Privilegedaction () {public Object run () { if (Loadproviderfromproperty ()) Return provider;if (Loadproviderasservice ()) Return Provider;provider = Sun.nio.ch.DefaultSelectorProvider.create (); return provider;}});}}
where Provider = Sun.nio.ch.DefaultSelectorProvider.create (), depending on the operating system to return different implementation classes, the Windows platform will return windowsselectorprovider;
Here mainly in the implementation of Windows to comb the entire process, get provider later see Openselector () implementation
Windowsselectorprovider.java----Public Abstractselector openselector () throws IOException {return new Windowsselectorimpl (this);} Windowsselectorimpl.java----Windowsselectorimpl (Selectorprovider sp) throws IOException {super (sp);p ollwrapper = new Pollarraywrapper (init_cap); wakeuppipe = Pipe.open (); wakeupsourcefd = ((Selchimpl) Wakeuppipe.source ()). GetFDVal (); /Disable The Nagle algorithm so, the wakeup is more immediatesinkchannelimpl sink = (Sinkchannelimpl) Wakeuppipe.sink ( );(Sink.sc). Socket (). Settcpnodelay (true); wakeupsinkfd = ((Selchimpl) sink). Getfdval ();p Ollwrapper.addwakeupsocket (WAKEUPSOURCEFD, 0);}
Here are a few things to do in this code
Pipe.open () Open a pipe (see after opening the implementation of the pipeline), get the WAKEUPSOURCEFD and wakeupsinkfd two file descriptors, and put the wake-up file descriptor (WAKEUPSOURCEFD) into the pollwrapper;
So why do you need a pipeline, and how is this pipeline implemented? Next See what Pipe.open () has done
Pipe.java----public static Pipe open () throws IOException {return Selectorprovider.provider (). Openpipe ();}
Similarly, Selectorprovider.provider () is also getting operating system-related implementations
Selectorprovider.java----Public Pipe openpipe () throws IOException {return new Pipeimpl (this);}
Here's a look at the implementation under Windows
Pipeimpl.java----Pipeimpl (final Selectorprovider sp) throws IOException {try {accesscontroller.doprivileged (new Initializer (SP));} catch (Privilegedactionexception x) {throw (IOException) X.getcause ();}}
A Pipeimpl object is created, and the initializer run method is executed immediately after the accesscontroller.doprivileged call
Pipeimpl.initializer-----Public Object Run () throws IOException {Serversocketchannel SSC = null; Socketchannel SC1 = null; Socketchannel SC2 = null;try {//loopback addressinetaddress lb = inetaddress.getbyname ("127.0.0.1"); Assert ( Lb.isloopbackaddress ());//Bind Serversocketchannel to a port on the loopback ADDRESSSSC = Serversocketchannel.open (); SSC . Socket (). bind (New inetsocketaddress (lb, 0));//Establish connection (assumes connections is eagerly//accepted) Inetsocketaddress sa= New Inetsocketaddress (LB, Ssc.socket (). Getlocalport ()); SC1 = Socketchannel.open (SA); Bytebuffer BB = bytebuffer.allocate (8), Long secret = Rnd.nextlong (); Bb.putlong (Secret). Flip (); Sc1.write (BB);//Get A Connection and verify it is legitimatefor (;;) {SC2 = Ssc.accept (); Bb.clear (); Sc2.read (BB); Bb.rewind (); if (bb.getlong () = = secret) Break;sc2.close ();} Create source and sink Channelssource = new Sourcechannelimpl (sp, SC1); sink = new Sinkchannelimpl (sp, SC2);} catch (IOException e) {try {if (SC1! = null) sc1.close(); if (SC2! = null) Sc2.close ();} catch (IOException E2) {}ioexception x = new IOException ("Unable to establish" + "loopback connection"); X.initcause (e); th Row x;} Finally {try {if (SSC! = null) Ssc.close ();} catch (IOException E2) {}}return null;}
This is the bottom part of the process of creating a pipe, the implementation of Windows is to create two local socketchannel, and then connect (the link process by writing a random long do two socket link check), Two Socketchannel respectively realized the source and sink end of the pipeline.
Source driven by the Windowsselectorimpl mentioned earlier in the Pollwrapper (Pollwrapper.addwakeupsocket (WAKEUPSOURCEFD, 0))
Pollarraywrapper.java----private Allocatednativeobject pollarray; The FD array//Adds Windows Wakeup socket at a given index.void addwakeupsocket (int fdval, int. index) {Putdescriptor (in Dex, Fdval);p uteventops (index, Pollin);} Access methods for FD structuresvoid putdescriptor (int i, int fd) {pollarray.putint (SIZE_POLLFD * i + fd_offset, FD);} void Puteventops (int i, int event) {Pollarray.putshort (SIZE_POLLFD * i + event_offset, (short) event);}
The Pollin event of source is identified as interesting, and when data is written to the sink end, the file descriptor wakeupsourcefd for the source is in the Ready state
Allocatednativeobject.java----Class Allocatednativeobject extends Nativeobjectallocatednativeobject (int size, Boolean pagealigned) {super (size, pagealigned);} Nativeobject.java----protected NativeObject (int size, Boolean pagealigned) {if (!pagealigned) {this.allocationaddress = unsafe.allocatememory (size); this.address = this.allocationaddress;} else {int ps = pageSize (); Long a = unsafe.allocatememory (size + PS); this.allocationaddress = A;this.address = A + PS-(a & (Ps-1));}}
From the above you can see that Pollarray is a piece of system memory allocated by Unsafe.allocatememory (size + PS)
To complete the Selector.open (), the main completion of the establishment of pipe, and the pipe wakeupsourcefd into the Pollarray, this pollarray is the hub of selector. Here is the implementation of Windows, under Windows through the two link Socketchannel implementation of the Pipe,linux is the direct use of the system pipe.
2. Serversocketchannel.register (selector, selectionkey.op_accept);
--Abstractselectablechannel.java Register ()-Selectorimpl.java----protected final Selectionkey register ( Abstractselectablechannel ch,int ops,object Attachment) {if (!) ( CH instanceof Selchimpl)) throw new Illegalselectorexception (); Selectionkeyimpl k = new Selectionkeyimpl ((SELCHIMPL) ch, this); K.attach (attachment); synchronized (Publickeys) { Implregister (k);} K.interestops (OPS); return k;}
The key is Implregister (k);
Windowsselectorimpl.java----protected void Implregister (Selectionkeyimpl ski) {growifneeded (); channelarray[ Totalchannels] = Ski;ski.setindex (totalchannels); Fdmap.put (ski); Keys.add (ski);p Ollwrapper.addentry (totalChannels , ski); totalchannels++;} Pollarraywrapper.java----void addentry (int index, Selectionkeyimpl ski) {putdescriptor (index, Ski.channel.getFDVal () );}
This puts the Socketchannel file descriptor in the Pollarray.
3. Selector.select ();
Selectorimpl.java----public int Select (long timeout) throws Ioexception{if (Timeout < 0) throw new IllegalArgumentException ("negative timeout"), return Lockanddoselect ((timeout = = 0) -1:timeout); private int Lockanddoselect (long timeout) throws IOException {synchronized (this) {if (!isopen ()) throw new Closedselector Exception (); synchronized (Publickeys) {synchronized (Publicselectedkeys) {return doselect (timeout);}}}
One of the doselector is back to our Windows implementation:
Windowsselectorimpl.java----protected int doselect (long timeout) throws IOException {if (Channelarray = null) throw new C Losedselectorexception (); this.timeout = timeout; Set selector timeoutprocessderegisterqueue (); if (interrupttriggered) {resetwakeupsocket (); return 0;} Calculate Number of helper threads needed for poll. If necessary//Threads is created here and start waiting on Startlockadjustthreadscount (); Finishlock.reset (); Reset finishlock//Wakeup Helper threads, waiting on Startlock, so they start polling.//redundant threads would exit he Re after wakeup.startLock.startThreads ();//Do polling in the main thread. Main thread is responsible for//first Max_selectable_fds entries in Pollarray.try {begin (); try {subselector.poll ();} CATC H (IOException e) {finishlock.setexception (e);//Save This exception}//Main thread was out of poll (). Wakeup others and wait for THEMIF (threads.size () > 0) finishlock.waitforhelperthreads (); } finally {end (); }//done with poll (). Set Wakeupsocket to nonsignaled for the next run.finishLock.checkForException ();p rocessderegisterqueue (); int updated = UPDA Teselectedkeys ();//Done with poll (). Set Wakeupsocket to nonsignaled for the next Run.resetwakeupsocket (); return updated;} private int Poll () throws ioexception{//poll for the main Threadreturn poll0 (pollwrapper.pollarrayaddress, Math.min (Tota Lchannels, Max_selectable_fds), Readfds, Writefds, Exceptfds, timeout);}
Private native int poll0 (long polladdress, int Numfds, int[] Readfds, int[] Writefds, int[] Exceptfds, long timeout);
The rest is some prep work, the key is Subselector.poll (), and finally called the native Poll0, And the pollwrapper.pollarrayaddress as a parameter to Poll0, then poll0 to Pollarray do what:
WINDOWSSELECTORIMPL.C----java_sun_nio_ch_windowsselectorimpl_00024subselector_poll0 (JNIEnv *env, Jobject this, Jlong polladdress, Jint Numfds, jintarray Returnreadfds, Jintarray Returnwritefds, Jintarray Returnexceptfds, Jlong timeout) { //code .... Omit 10,000 words/* Call SELECT */ if (result = Select (0, &readfds, &writefds, &EXCEPTFDS, TV)) = = Socket_error) { Code.... This omits 10,000 words for (i = 0; i < Numfds; i++) {//code .... Omit 10,000 Words}}}
C code is almost forgotten, but here you can see that the implementation of the idea is to call C's Select method, where the select corresponds to the kernel of the Sys_select call, Sys_select first the No. 234 parameter points to the fd_set copy to the kernel, Each set descriptor call is then poll and recorded in the temporary result (fdset), and if an event occurs, select writes the temporary result to the user space and returns, and if the timeout is specified when no event occurs after polling, then select sleeps to timeout. After the sleep is completed, a poll is made and the temporary results are written to the user space and then returned.
The select here is to poll the FD in the Pollarray to see if there are any events occurring, and if there is an event that collects all occurrences of FD, the exit is blocked.
About select system Call Reference "Select, poll, epoll comparison" This article, while see NiO's Select on different platforms implementation is different, on Linux through Epoll can not poll, after the first call, The event information is associated with the corresponding Epoll descriptor, and the callback function is registered on the descriptor, and when the event occurs, the callback function is responsible for storing the event in the Ready Event list and finally writing to the user space.
Here it is clear that the way to exit the block is: Regist on the selector socketchannel is in the Ready state (Socketchannel in Pollarray in the FD Ready) or WAKEUPSOURCEFD ready in the 1th section in Pollarray. The former (Socketchannel) ready wake-up should be validated by the start of the article, the event-driven wake-up process, the latter (WAKEUPSOURCEFD) is the following to see the active wakeup.
4. Selector.wakeup ()
Windowsselectorimpl.java----Public Selector wakeup () {synchronized (Interruptlock) {if (!interrupttriggered) { Setwakeupsocket (); interrupttriggered = True;}} return this;} Sets Windows wakeup socket to a signaled state.private void Setwakeupsocket () {setWakeupSocket0 (WAKEUPSINKFD);} Private native void setWakeupSocket0 (int wakeupsinkfd);
Native Implementation Summary:
WINDOWSSELECTORIMPL.C----Java_sun_nio_ch_windowsselectorimpl_setwakeupsocket0 (jnienv *env, Jclass this, jint SCOUTFD) {/ * Write one byte into the pipe * /Send (SCOUTFD, (char*) &pollin, 1, 0);}
This completes the sink end of the pipe that was first established, writes a byte, the source file descriptor is in the ready state, and the poll method returns, causing the Select method to return. (originally set up a socket chain of their own another socket is to do this)
By the source analysis, the principle of selector blocking wake is cleared.
Reference Study Articles:
Http://www.cnblogs.com/xuxm2007/archive/2011/08/15/2139809.html
Http://blog.chinaunix.net/uid-20543672-id-3267385.html
http://goon.iteye.com/blog/1775421
http://blog.csdn.net/aesop_wubo/article/details/9117655
The principle of NiO Selector blocking wake